[英]Joi Validations: If object matches the schema validate against it from multiple items
我有一组对象要根据特定模式进行验证,如果任何对象与给定模式匹配,我想对其进行验证并忽略其他模式并移至下一个数组项。
我试过 Joi.alternatives 但它会 go 并检查所有模式,而不是只检查一个是否匹配。
我的验证器:
Joi.array().min(1).max(49).items(Joi.object({
type: Joi.number().valid([1, 2, 3, 4]).required()
}).when(Joi.object({
type: Joi.number().valid(1)
}).unknown(), {
then: profile1
}).when(Joi.object({
type: Joi.number().valid(2)
}).unknown(), {
then: profile2
}).when(Joi.object({
type: Joi.number().valid(3)
}).unknown(), {
then: profile3
}))
配置文件1//类型1
export default Joi.object().keys({
type: Joi.number().valid([1, 2, 3]).required(),
surname: Joi.string().max(50).allow(""),
givenname: Joi.string().max(50).allow("")
}).unknown(true)
配置文件2//类型2
export default Joi.object().keys({
type: Joi.number().valid([1, 2, 3]).required(),
address: Joi.string().max(50).allow(""),
initialname: Joi.string().max(50).allow(""),
surname: Joi.string().max(50).allow(""),
data: Joi.array.min(1).max(29).items(Joi.object({
code: Joi.string().max(20).allow(""),
number: Joi.string().max(20).allow(""),
}),
address1: Joi.array.min(1).max(29).items(Joi.object({
city: Joi.string().max(20).allow(""),
postal: Joi.string().max(20).allow(""),
})
}).unknown(true)
配置文件3//类型3
export default Joi.object().keys({
type: Joi.number().valid([1, 2, 3]).required(),
units: Joi.string().max(50).allow(""),
others: Joi.string().max(50).allow(""),
surname: Joi.string().max(50).allow(""),
data2: Joi.array.min(1).max(29).items(Joi.object({
sub1: Joi.string().max(20).allow(""),
sub2: Joi.string().max(20).allow(""),
}),
additional: Joi.array.min(1).max(29).items(Joi.object({
data1: Joi.string().max(20).allow(""),
data2: Joi.string().max(20).allow(""),
})
}).unknown(true)
样本 object:
[
{
"type":1,
"surname":"",
"givenname":""
},
{
"type":2,
"surname":"val",
"address":"testte",
"initialname":"test",
"data":[{
"code":"test",
"number":"test"
}],
"address1":[{
"city":"test",
"postal":123
}
}],
{
"type":"3",
"surname":"",
"units":"",
"others":"",
"data2":[{
"sub1":"test",
"sub2":"test"
}],
"additionals":[{
"data1":"test",
"data2":123
}]
}
]
这里 profile1 与给定数据匹配,因此它应该针对它进行验证并忽略 profile2 和 profile3(也验证类型是数字)
这里 profile2 与给定数据匹配,因此它应该针对它进行验证并忽略 profile1 和 profile3(也验证类型是数字)
现在它应该从类型不是数字的数组移动到下一个 object 所以它不应该检查模式并抛出错误
注意:我使用的是 Joi 版本 13.4.0
您的文件和验证器中有一些拼写错误。
Joi.array 的第一个是 function,需要作为一个调用。
// This is incorrect
data2: Joi.array
...
additional: Joi.array
// Should be changed to this where array is invoked as a function
data2: Joi.array()
...
additional: Joi.array()
此外,我添加了第四个验证器,它基本上通过了类型大于 3 的所有示例对象。
.when(
Joi.object({
type: Joi.number().greater(3),
}).unknown(),
{
then: Joi.object().unknown(true),
}
)
您的验证器中还有其他拼写错误,例如缺少括号 - 我在codesandbox中创建了您的验证器的固定版本。
codesandbox 中的验证仍然失败,因为在 profile2.js 中邮政被声明为字符串,但在您的示例数组中它是第二个 object 的数字,搜索邮政:123并将其更改为邮政:“123”或修改验证邮政从邮政:Joi.string()到邮政:Joi.number()
这样,如果其中一个验证器通过,那么其他验证器就不会抛出错误,如果类型大于 3,它将通过验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.