YUP 验证:将字段“a”和“b”的数学值与字段“c”进行比较

问题描述 投票:0回答:3

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

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

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

如果((field_1 * field_2}< field_3) { return an error }

我通过阅读文档了解到您可以向 yup 添加自定义方法(即:addMethod),但到目前为止我未能使这种方法起作用。

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

reactjs validation formik yup
3个回答
9
投票

我终于找到了一个我可以使用的例子。我在 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;
    }),

6
投票

您可以在

this.parent['sibling_form_field_id']
函数中使用
test
通过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;
    },
  );

0
投票

您可以根据项目需求使用此模式

const Schema = Yup.object().shape({

  sellMinAmount: Yup. number(),

  sellMaxAmount: Yup. number(),

  btcAmount:Yup.number("please enter only no")

    .test("Is greater than sell MIn mount?",

  "sellMinTrade Validation Error",  
          
  (value,sellMinTrade) => { 

    const customError = `The sell field must be greater than 50 or more`;

    if(value < sellMinTrade?.parent.sellMinAmount) {

       return sellMinTrade.createError({message: customError });  
   
    }
    else {
       return true;
    }
  }  
});

© www.soinside.com 2019 - 2024. All rights reserved.