我有一个对象数组要从特定模式进行验证,如果任何对象与给定模式匹配,我想对其进行验证并忽略其他模式并移至下一个数组项。
我尝试了 Joi.alternatives,但它会检查所有模式,而不是仅检查一个匹配的模式。
我的验证器:
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
}))
Run Code Online (Sandbox Code Playgroud)
配置文件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)
Run Code Online (Sandbox Code Playgroud)
配置文件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)
Run Code Online (Sandbox Code Playgroud)
配置文件3//类型3
export default Joi.object().keys({
type: Joi.number().valid([1, …Run Code Online (Sandbox Code Playgroud)