1
votes

Hello I am quite new to YUP and trying to like it :)

I am able to get yup to do the basic (built-in) validation stuff, but I can't seem to figure out how to do validation that involves a bit of math.

For instance, I'm aware that you can use Yup.ref('field') and .lessThan to validate field_1 against field_2, but what if you wanted to do something like this?

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

I am aware by reading the documentation that you can add custom methods (ie: addMethod) to yup, but I have failed to make this approach work so far.

Any help or a link to a solid example of how to use addMethod in this manner would be greatly appreciated. Thanks in advance.

2

2 Answers

8
votes

I finally found an example I could use. I used the '.test' object in YUP and wrote a function. Sorry for the newbie questions. Here is my resolution:

.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;
    }),
4
votes

You can use this.parent['sibling_form_field_id'] inside the test function to retrieve the values of the other form fields by id.

So you can do this:

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;
    },
  );