Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the value of another field for validation in Yup Schema

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?

like image 789
Michael Edwards Avatar asked Jul 23 '20 16:07

Michael Edwards


1 Answers

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.

like image 66
tatsuya kanemoto Avatar answered Sep 20 '22 09:09

tatsuya kanemoto