【问题标题】:YUP validation: compare mathematical values of fields 'a' and 'b' to field 'c'YUP 验证:将字段“a”和“b”的数学值与字段“c”进行比较
【发布时间】:2019-04-17 19:44:46
【问题描述】:

你好,我对 YUP 很陌生,我很想喜欢它 :)

我能够让 yup 进行基本(内置)验证工作,但我似乎无法弄清楚如何进行涉及一些数学的验证。

例如,我知道您可以使用 Yup.ref('field') 和 .lessThan 来验证 field_1 与 field_2,但如果您想做这样的事情怎么办?

if ((field_1 * field_2}

通过阅读文档,我知道您可以将自定义方法(即:addMethod)添加到是的,但是到目前为止我还没有使这种方法起作用。

任何帮助或指向如何以这种方式使用 addMethod 的可靠示例的链接将不胜感激。提前致谢。

【问题讨论】:

    标签: reactjs validation formik yup


    【解决方案1】:

    我终于找到了一个可以使用的例子。我在 YUP 中使用了“.test”对象并编写了一个函数。抱歉新手问题。这是我的解决方案:

    .test('test-compare a few values', 'U suck at math (this is the failure message for the test)',
       function(value) {
        let value1 = this.resolve(Yup.ref("1st_number"));
        let value2 = this.resolve(Yup.ref("2nd_number"));
        let value3 = this.resolve(Yup.ref("3rd_number"));
        if((value1 * value2) > value3)
             return false;
        else
             return true;
        }),
    

    【讨论】:

    • 我得到了ReferenceError: Yup is not defined,所以我会选择this.parent.fieldName
    • @Tamas 大多数人都使用import * as Yup from "yup"。也许这就是这段代码的设置方式。
    【解决方案2】:

    您可以在test 函数中使用this.parent['sibling_form_field_id'] 来通过id 检索其他表单字段的值。

    所以你可以这样做:

    YUP.string()
      .test('test-compare a few values', 'U suck at math (this is the failure message for the test)',
        function (value) { // beware, don't use arrow function here otherwise you would not the reference to `this` object
          let value1 = this.parent['1st_number']; // retrieve the value of the sibling form field with id `1st_number`
          let value2 = this.parent['2nd_number']; // retrieve the value of the sibling form field with id `2nd_number`
          let value3 = this.parent['3rd_number']; // retrieve the value of the sibling form field with id `3rd_number`
          if ((value1 * value2) > value3)
            return false;
          else
            return true;
        },
      );
    

    【讨论】:

    • 不错,注意不能使用箭头函数,否则this 将是未定义的
    猜你喜欢
    • 2016-02-19
    • 2020-11-19
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多