如何在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
相关产品推荐
相关产品推荐

