Categories
JavaScript Answers

How to Add Conditional Form Field Validation in Yup?

Spread the love

We can validate a field conditionality with Yup by using the when method.

For instance, we can write:

validationSchema={yup.object().shape({
  showName: yup.boolean(),
  name: yup
    .string()
    .when("showName", {
      is: true,
      then: yup.string().required("name is required")
    })
  })
}

We have the showName boolean field.

And we only validate the name field when it’s true as indicated in the is field.

then lets us do the validation only when showName is true .

Then we return the 'name is required' message if it is.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *