是的,如何根据其他几个变量的函数验证一个变量?

Yup, how to validate one variable against a function of several other ones?

我正在尝试实施一个 yup 验证模式,假设我有五个数值(A、B、C、D、E)

我希望 D 和 E 小于基于 A、B、C 和某个常数值的数学函数。像这样:

const upperBound = Math.min(A,B,C)-10;
if((D > upperBound) || (E > upperBound))
    return FAIL;
else
    return PASS;

我已经审查了很多关于 SO 的线程,但是 none 其中解决了多变量依赖性问题。 谢谢

您可以使用测试函数来实现:

Yup.object().test({
          name: 'D and E less than ABC', // Your custom error id
          test: function () {
             const {A,B,C,D,E} = this.parent; // Access the object data, here this.parent contains your data
             const upperBound = Math.min(A,B,C)-10;
             if((D > upperBound) || (E > upperBound))
                 return this.createError({
                  message: `D and E must be below min`, // Error message for the user
                  path: `D`, // The object path where you want show the error
                });
             return true; // True for no error
        }),