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

Joi仅当属性b不为undefined时添加a≤b校验规则报错如何解决

报错原因

你遇到的报错是因为在when方法的is条件中直接使用Joi.not(undefined)不符合Joi的API规范,Joi不允许直接向not方法传入undefined作为校验值,因此触发了该错误:

Cannot call allow/valid/invalid with undefined

同时你原有代码还存在语法问题:a属性的定义里少了when方法的闭合括号,且不必要地使用了concat方法增加了代码复杂度。

修正后的实现代码
const mySchema = Joi.object().keys({
    a: Joi.number().when('b', { 
        is: Joi.exist(), 
        then: Joi.number().max(Joi.ref('b')).message('a should be less than or equal to b') 
    }),
    b: Joi.number() 
})
规则说明
  • 如果你需要严格仅排除undefined(b为null时不需要触发a的校验),可以把is: Joi.exist()替换为is: Joi.not().undefined()即可
  • Joi.exist()的默认逻辑是校验目标属性既不是undefined也不是null,符合绝大多数场景的“属性存在且有有效值”的判断需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:45:04