[英]JOI - Validating complex object
I tried, and tried but can't figure it :(我试过,试过,但想不通:(
This is the object I need to validate:这是我需要验证的对象:
let body = {
greeting:
{
stringValue: 'Hello !',
stringListValues: [],
binaryListValues: [],
dataType: 'String'
},
newsletterId:
{
stringValue: '123456789',
stringListValues: [],
binaryListValues: [],
dataType: 'String'
}
};
I need to validate that there is a greeting , and that is has key stringValue and that is not empty.我需要验证有一个greeting ,并且它有 key stringValue并且它不是空的。 Other values I don't care.其他值我不在乎。
Also, for the second object newsletterId , and that also has key stringValue and that is not empty.此外,对于第二个对象newsletterId ,它也有键stringValue并且不为空。 Other values I don't care.其他值我不在乎。
I have come up with checking only root object, with this schema:我想出了只检查根对象,使用这个架构:
const schema = {
greeting: Joi.required(),
newsletterId: Joi.required()
};
I read many examples, but I was unable to find none that has this type of structure.我阅读了很多示例,但找不到具有这种结构的示例。
lets define a schema :让我们定义一个架构:
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
});
and test it like this :并像这样测试它:
Joi.validate(myObjectToTest, schema, function(error, cleanObject){
console.log(error, cleanObject);
})
Full reference can be found here https://github.com/hapijs/joi/blob/master/API.md完整参考可以在这里找到https://github.com/hapijs/joi/blob/master/API.md
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.