You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 15:01:05