Conditional validation in Yup

by admin
yup-image

Yup (found here) can be awesome, it can also be tricky sometimes. For example, conditional validation based on another field may be difficult.

Let’s say we want to base whether something is required, based on another field. How can we achieve that?

In the example below I have a checkbox in my form which is called ‘isVisibleForCarrier’. Whenever this checkbox is checked, I want to limit the maximum amount of characters a user can enter in a textinput. So I configured my validation schema as follows:

const validationSchema = Yup.object().shape({
  note: Yup.string().when('isVisibleForCarrier', {
    is: true,
    then: () => Yup.string().required().max(254).label('Note'),
    otherwise: () => Yup.string().max(2000).required().label('Note')
  })
})

As you can see above, I am checking whether isVisibleForCarrier is true, if so, in the then() function I specify a max length of 254, and the field is required. When the value equals false, I have a max length of 2000 characters.

That is how you configure conditional validation in Yup :).

Related Posts

Leave a Comment