我正在尝试使用joi进行条件验证。代码在下面
const Joi = require('joi');
const joiSampleSchema = Joi.object().keys({
data: Joi.object().keys({
param1: Joi.string().required(),
param2: Joi.string().required(),
alphabets: Joi.array().items({
name: Joi.string().required(),
numbers: Joi.array().items({
first: Joi.optional(),
second: Joi.optional(),
name: Joi.string().when(
'first', {
is: '',
then: Joi.optional(),
otherwise: Joi.string().required()
}),
name1: Joi.string().when(
'first', {
is: '',
then: Joi.optional(),
otherwise: Joi.string().required()
}),
class: Joi.string().when(
'second', {
is: '',
then: Joi.optional(),
otherwise: Joi.string().required()
}),
class1: Joi.string().when(
'second', {
is: '',
then: Joi.optional(),
otherwise: Joi.string().required()
}),
})
})
})
});
const options = {
allowUnknown: true
, stripUnknown: false
}
const result = Joi.validate(joisamplejson, joiSampleSchema, options);
if (result.error && result.error.details) {
result.error.details.forEach(function (error) {
console.log('Errored parameter: '+error.path.join("."));
});
};
下面是我要验证的json
{
"data": {
"param1": "param1value",
"param2": "param2value",
"alphabets": [
{
"name": "a",
"numbers": [
{
"first": "",
"second": "dafe",
"name": "",
"name1": "peter1",
"class": "kekk",
"class1":"kekk1"
},
{
"first": "asd",
"second": "dafe",
"name": "james",
"name1": "james1",
"class": "jejj",
"class1":"jejj1"
}
]
}
]
}
}
我要针对这种情况进行验证:
在“数字”数组中,当参数“第一”为空字符串或未定义时,在验证时应忽略参数“名称”和“名称1”。如果参数“ first”的值是一个非空字符串,则参数“名称”和“ name1”的值应是非空字符串。同样的情况适用于参数“ second”,“ class”和“ class1”。
但是上面的代码无法实现这一点。请帮忙。
预先感谢