Moh*_*h M 1 javascript node.js express joi
我有几个验证器文件,其中包含近一百个模式对象。我想同时验证所有这些密钥的未知密钥。我已经找到了一种方法来验证我在下面发布的一个对象的未知密钥。有没有一种方法可以一次性完成所有事情?我正在寻找一种干的方法来做到这一点。
const schema = Joi.object().keys({
a: Joi.string().required(),
b: Joi.string().required()
}).unknown(true);
// or
const schema = Joi.object().keys({
a: Joi.string().required(),
b: Joi.string().required()
}).options({ allowUnknown: true })
Run Code Online (Sandbox Code Playgroud)
You can use .defaults to create your own custom joi which in this case will have allowUnkown set true as default:
// Create your custom Joi
const customJoi = Joi.defaults((schema) => schema.options({
allowUnknown: true
}));
// schema using original Joi
const schema1 = Joi.object().keys({
a: Joi.string().required(),
b: Joi.string().required()
})
// schema using custom Joi
const schema2 = customJoi.object().keys({
a: Joi.string().required(),
b: Joi.string().required()
})
// INVALID, "c" is not allowd
schema1.validate({ a: "a", b: "b", c: 10 })
// VALID
schema2.validate({ a: "a", b: "b", c: 10 })
Run Code Online (Sandbox Code Playgroud)
This also works:
var Joi = require("joi").defaults((schema) => schema.options({
allowUnknown: true
}));
Run Code Online (Sandbox Code Playgroud)
or
var Joi = require("joi")
Joi = Joi.defaults((schema) => schema.options({
allowUnknown: true
}));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5135 次 |
| 最近记录: |