JOI - 验证复杂对象
JOI - Validating complex object
我试了又试,但想不通:(
这是我需要验证的对象:
let body = {
greeting:
{
stringValue: 'Hello !',
stringListValues: [],
binaryListValues: [],
dataType: 'String'
},
newsletterId:
{
stringValue: '123456789',
stringListValues: [],
binaryListValues: [],
dataType: 'String'
}
};
我需要验证有一个 greeting,它有键 stringValue 并且不为空。其他值我不关心。
此外,对于第二个对象 newsletterId,它也有键 stringValue 并且不为空。其他值我不关心。
我想到了只检查根对象,使用这个模式:
const schema = {
greeting: Joi.required(),
newsletterId: Joi.required()
};
我看了很多例子,但是我找不到none有这种结构的。
让我们定义一个模式:
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);
})
我试了又试,但想不通:(
这是我需要验证的对象:
let body = {
greeting:
{
stringValue: 'Hello !',
stringListValues: [],
binaryListValues: [],
dataType: 'String'
},
newsletterId:
{
stringValue: '123456789',
stringListValues: [],
binaryListValues: [],
dataType: 'String'
}
};
我需要验证有一个 greeting,它有键 stringValue 并且不为空。其他值我不关心。
此外,对于第二个对象 newsletterId,它也有键 stringValue 并且不为空。其他值我不关心。
我想到了只检查根对象,使用这个模式:
const schema = {
greeting: Joi.required(),
newsletterId: Joi.required()
};
我看了很多例子,但是我找不到none有这种结构的。
让我们定义一个模式:
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);
})