【问题标题】:How to validate sum of refs in Joi如何验证 Joi 中的参考总和
【发布时间】:2021-12-23 10:50:42
【问题描述】:

如何验证以下两个参考的总数?我希望customtotal 上,但不确定在使用Joi.ref 时如何在自定义中获取refs 的值。

我可以执行以下操作并将 custom 从整个验证架构中挂起,但更愿意将其附加到 total

我不想使用expression()

我不希望按照this answer 更改架构结构。

  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((value: {a: number; b: number; total: number;}, helpers) => {
      if (value.total !== value.a + value.b) {
        throw new Error('invalid balance calculation');
      }

      return value;
    },
  );

【问题讨论】:

    标签: javascript typescript joi


    【解决方案1】:

    当您在属性上安装custom 时,获取整个对象值会有点困难。你必须从helpers's states获得它:

    Joi.object({
        a: Joi.number().integer().min(0).required(),
        b: Joi.number().integer().min(1).required(),
        total: Joi.number().integer().min(1).required().custom((value, helpers) => {
          const { a, b } = helpers.state.ancestors[0];
          if (value !== a + b) {
            throw new Error('invalid balance calculation');
          }
    
          return value;
        },
      )
    })
    

    【讨论】:

    • 谢谢,TS 需要一些演员,但效果很好。
    猜你喜欢
    • 1970-01-01
    • 2020-06-04
    • 2015-10-17
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 2019-12-13
    相关资源
    最近更新 更多