JOI
我试过了,尝试,但不能图:(
这是我需要验证的对象:
let body = {
greeting:
{
stringValue: 'Hello !',
stringListValues: [],
binaryListValues: [],
dataType: 'String'
},
newsletterId:
{
stringValue: '123456789',
stringListValues: [],
binaryListValues: [],
dataType: 'String'
}
};
我需要验证,有一个问候,这是具有关键stringValue的,这是不是空的。我不关心其他值。
此外,对于第二个对象newsletterId,并且还具有关键stringValue的,这是不是空的。我不关心其他值。
我想出了只检查根对象,这种模式:
const schema = {
greeting: Joi.required(),
newsletterId: Joi.required()
};
我看过很多例子,但我无法找到没有拥有这种类型的结构。
回答如下:可以定义一个模式:
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
});
并测试它是这样的:
Joi.validate(myObjectToTest, schema, function(error, cleanObject){
console.log(error, cleanObject);
})
完整的参考可以在这里找到https://github/hapijs/joi/blob/master/API.md