Joi 13.4.0数组对象匹配Schema后终止其他验证问题
问题:Joi数组对象按type匹配对应Schema验证,匹配后终止其他Schema检查
我需要验证一个对象数组,要求数组中每个对象匹配对应Schema后,仅按该Schema进行验证,跳过其他Schema,再处理下一个数组元素。此前尝试使用Joi.alternatives,但它会检查所有Schema而非匹配后终止验证。当前使用Joi版本为13.4.0,现有验证器及Profile1-3代码如下:
我的验证器:
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 }))
Profile1//type1
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)
Profile2//type2
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)
Profile3//type3
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)
具体需求:
- 匹配Profile1后,仅验证该Schema,忽略Profile2和Profile3
- 多数组对象场景下,仅验证对应匹配的Profile
- 示例对象中,若type非数字,需抛出错误
示例对象:
[ { "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 }] } ]
内容的提问来源于stack exchange,提问作者Bravo
相关产品推荐
相关产品推荐

