使用Joi进行验证时对未知密钥进行条带化

时间:2015-07-28 14:32:35

标签: javascript node.js joi

我使用Joi来验证服务器中的JavaScript对象。架构如下所示:

var schema = Joi.object().keys({
    displayName: Joi.string().required(),
    email: Joi.string().email(),
    enabled: Joi.boolean().default(false, "Default as disabled")
}).unknown(false);

如果对象中存在未知密钥,上面的模式将报告错误,这是预期的,但我想要的是静默地剥离所有未知,而没有错误。是否有可能完成?

4 个答案:

答案 0 :(得分:5)

You need to use the stripUnknown option if you want to strip the unknown keys from the objects that you are validating.

cf options on https://github.com/hapijs/joi/blob/master/API.md#validatevalue-schema-options-callback

答案 1 :(得分:1)

与版本 14.3.4 一样,此问题有一个简单的解决方案。这是为您解决问题的代码。

// Sample data for testing.
const user = {
    fullname: "jayant malik",
    email: "demo@mail.com",
    password: "password111",
    username: "hello",
    name: "Hello"
};

// You define your schema here
const user_schema = joi
  .object({
    fullname: joi.string().min(4).max(30).trim(),
    email: joi.string().email().required().min(10).max(50).trim(),
    password: joi.string().min(6).max(20),
    username: joi.string().min(5).max(20).alphanum().trim()
  })
  .options({ stripUnknown: true });

// You validate the object here.
const result = user_schema.validate(user);

// Here is your final result with unknown keys trimmed from object.
console.log("Object with trimmed keys: ", result.value);

答案 2 :(得分:0)

NxK

答案 3 :(得分:0)

这是当前包含条带未知选项的方法:

const validated = customSchema.validate(objForValidation, { stripUnknown: true });

如果您传递的objForValidation的密钥未在customSchema中定义,它将在验证之前删除该条目。