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

JOI验证when条件未按预期生效,求排查Schema定义问题

问题分析与解决方案

你的Schema定义确实存在一个关键问题——嵌套对象里的when规则默认只会查找当前对象层级的字段,而你要引用的flag是在父级对象中的,所以不管flag设成什么,嵌套的amount和tool都找不到对应的字段,只能走otherwise分支。

修正方法

你需要使用Joi的ref()方法来明确引用父级的flag字段,具体来说就是把when('flag', ...)改成when(Joi.ref('..flag'), ...),其中..表示向上遍历一层父级对象。

这里是修正后的完整Schema:

const schema = Joi.object({ 
  flag: Joi.boolean().required(), 
  toolDetail: Joi.array().items( 
    Joi.object({ 
      amount: Joi.number()
        .min(0)
        .max(499.99)
        .precision(2)
        .options({ convert: false })
        .when(Joi.ref('..flag'), { 
          is: true, 
          then: Joi.number().required(), 
          otherwise: Joi.number().strip().optional().allow(''), 
        }), 
      tool: Joi.string()
        .min(0)
        .max(500)
        .when(Joi.ref('..flag'), { 
          is: true, 
          then: Joi.string().required(), 
          otherwise: Joi.string().strip().optional().allow(''), 
        }), 
    }), 
  ), 
});

补充说明

  • Joi.ref('..flag')的作用是告诉Joi:去当前对象的父级(也就是最外层的Joi.object)里找flag字段的值,这样就能正确触发对应的分支规则了。
  • 如果你有更深层级的嵌套,还可以用...来多级向上引用,比如Joi.ref('...flag')表示向上两层。

内容的提问来源于stack exchange,提问作者LessThan3 Vi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 08:37:43