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

如何在Joi的total字段custom校验中验证两个ref的总和

你可以直接在total字段的校验规则链上挂载custom方法,通过回调的第二个参数helpers提供的state.parent属性获取同层级其他字段的取值,无需调整现有Schema结构,也不需要用到expression()方法,实现代码如下:

const widgetValidator = Joi.object({
  a: Joi.number().integer().min(0).required(),
  b: Joi.number().integer().min(1).required(),
  total: Joi.number().integer().min(1).required()
    .custom((totalValue, helpers) => {
      const { a, b } = helpers.state.parent;
      if (totalValue !== a + b) {
        return helpers.error('any.invalid', { message: 'invalid balance calculation' });
        // 也可以沿用你原有写法直接抛出错误:throw new Error('invalid balance calculation')
      }
      return totalValue;
    })
});

实现说明

  • 字段级custom回调的第一个入参是当前total字段本身的校验值
  • helpers.state.parent指向当前字段所属的父级对象,也就是包含a、b、total三个字段的完整对象,可以直接读取另外两个字段的取值做加法校验
  • 使用helpers.error方法抛出校验错误符合Joi的官方错误处理规范,和直接抛Error的效果完全一致,可以根据你的使用习惯选择写法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 17:48:05