Home > other >  Yup validation, if a field is true, check the value of another field with switch statements
Yup validation, if a field is true, check the value of another field with switch statements

Time:12-15

Let's say I have 3 fields: showDiscount, discountType and discountValue.

When showDiscount is set to true and discountType is 'PERCENTAGE', discountValue should be required and should be from 1 to 100. If discountType is 'FIXED_AMOUNT', discountValue should at least be 0.01.

I tried searching for a solution and this is the closest I could find: Two Condition in When in Yup in React

After applying changes, here's a sample snippet:

const schema = yup.object().shape({
    showDiscount: yup.boolean().required(''),
    discountType: yup.string().when('showDiscount', {
      is: true,
      then: yup.string().required(),
    }),
    discountValue: yup.number().when('showDiscount', {
      is: (showDiscount) => showDiscount,
      then: yup
        .number()
        .when('discountType', (discountType, discountValueSchema) => {
          switch (discountType) {
            case 'PERCENTAGE':
              return discountValueSchema
                .typeError('Enter a number')
                .min(1, 'Enter a discount percentage of at least 1%')
                .max(100, 'Enter a discount percentage of at most 100%')
            case 'FIXED_AMOUNT':
              return discountValueSchema
                .typeError('Enter a number')
                .min(0.01, 'Enter a discount amount of at least 0.01')
            default:
              return discountValueSchema
          }
        }),
      })
    ),
})

When I try to submit the form regardless of the value of showDiscount and discountType, I'm getting the following error:

discountValue must be a number type, but the final value was: NaN (cast from the value "").

CodePudding user response:

when can accept multiple fields so you should be able to do

...
.when(['showDiscount', 'discountType'], (showDiscount, discountType, discountValueSchema) => {
...

While this example is not explicitly in the documentation, you can see this hinted here https://www.npmjs.com/package/yup#mixedwhenkeys-string--arraystring-builder-object--value-schema-schema-schema

  • Related