[英]Stripping unknown keys when validating with Joi
I'm using Joi to validate a JavaScript object in the server.我正在使用 Joi 来验证服务器中的 JavaScript 对象。 The schema is like the following:
架构如下所示:
var schema = Joi.object().keys({
displayName: Joi.string().required(),
email: Joi.string().email(),
enabled: Joi.boolean().default(false, "Default as disabled")
}).unknown(false);
The schema above will report an error if there is an unknown key in the object, which is expected, but what I want is to strip all the unknown silently, without an error.如果对象中存在未知键,则上面的架构将报告错误,这是预期的,但我想要的是静默剥离所有未知,而不会出错。 Is it possible to be done?
有没有可能做到?
You need to use the stripUnknown
option if you want to strip the unknown keys from the objects that you are validating.如果要从正在验证的对象中
stripUnknown
未知键,则需要使用stripUnknown
选项。
cf options on https://github.com/hapijs/joi/blob/master/API.md#validatevalue-schema-options-callback https://github.com/hapijs/joi/blob/master/API.md#validatevalue-schema-options-callback 上的cf 选项
const joi = require('joi');
joi.validate(object, schema, {stripUnknown:true}, callback);
As in Version 14.3.4, there is a simple solution to this issue.与版本 14.3.4 一样,此问题有一个简单的解决方案。 Here is the code that solves the problem for you.
这是为您解决问题的代码。
// 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);
Here is the current way to include the strip unknown option:这是包含条带未知选项的当前方法:
const validated = customSchema.validate(objForValidation, { stripUnknown: true });
If you pass in an objForValidation
that has a key which isn't defined in your customSchema
, it will remove that entry before validating.如果您传入的
objForValidation
具有未在customSchema
定义的customSchema
,它将在验证之前删除该条目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.