Ved*_*ic. 3 javascript node.js joi
我尝试了,尝试了,但无法弄清楚:(
这是我需要验证的对象:
let body = {
greeting:
{
stringValue: 'Hello !',
stringListValues: [],
binaryListValues: [],
dataType: 'String'
},
newsletterId:
{
stringValue: '123456789',
stringListValues: [],
binaryListValues: [],
dataType: 'String'
}
};
Run Code Online (Sandbox Code Playgroud)
我需要验证是否有一个greeting,并且它有key stringValue并且不为空。其他值我不在乎。
另外,对于第二个对象newsletterId,它也有键stringValue并且不为空。其他值我不在乎。
我想出了只检查根对象,具有以下模式:
const schema = {
greeting: Joi.required(),
newsletterId: Joi.required()
};
Run Code Online (Sandbox Code Playgroud)
我读了很多例子,但我找不到任何具有这种结构的例子。
让我们定义一个模式:
const schema = Joi.object().keys({
greeting: Joi.object({
stringValue: Joi.string().required().empty(['', null]),
stringListValues: Joi.array().items(Joi.string()),
binaryListValues: Joi.array().items(Joi.binary())
}).required(),
newsletterId: // same as above
});
Run Code Online (Sandbox Code Playgroud)
并像这样测试它:
Joi.validate(myObjectToTest, schema, function(error, cleanObject){
console.log(error, cleanObject);
})
Run Code Online (Sandbox Code Playgroud)
完整参考可以在这里找到https://github.com/hapijs/joi/blob/master/API.md
| 归档时间: |
|
| 查看次数: |
5560 次 |
| 最近记录: |