8
votes

I am using Formik with Yup for validation and TypeScript

I have a field that needs to validate based on the value of another field.

The first field is called price and the second field is called tips. The max tip value is 10% of the what ever the price entered is.

I tried to create validation for this using the following:

   tips: yup.number()
    .min(0, `Minimum tip is $0`)
    .max( parseFloat(yup.ref('price'))* 0.1, "Maximum tip is 10% of the price.");

however this doesn't compile because yup.ref returns a Ref. How can I get the value of the price field in this validation?

1
Does yup.reach('price') help? From what I read here, you can access object schemas using reachDavid Buzatu

1 Answers

13
votes

number.max cannot reference other field and calculate with it at validation.

If you want to do this, you need to implement own schema with mixed.test.
Here is a example.

  tips: number()
    .min(0, `Minimum tip is $0`)
    .test({
      name: 'max',
      exclusive: false,
      params: { },
      message: '${path} must be less than 10% of the price',
      test: function (value) {
          // You can access the price field with `this.parent`.
          return value <= parseFloat(this.parent.price * 0.1)
      },
    }),

Here is doc.
You can check and try how it works here.

I hope this will help you.