Conditional Yup validation according to state variable

Viewed 2633

Is it possible to conditionally validate a text field using Yup resolver RHF, only when the state of a given variable is true.

I researched a lot but couldn't find an example.

Thanks

1 Answers

To use Yup.when for archiving condition base validation. Check more details yup

Example:

You can use Yup conditions

const validationSchema = Yup.object().shape({
  isCompany: Yup.boolean(),
  companyName: Yup.string().when('isCompany', {
    is: true,
    then: Yup.string().required('Field is required')
  }),
  companyAddress: Yup.string().when('isCompany', {
    is: (isCompany) => true,//just an e.g. you can return a function
    then: Yup.string().required('Field is required'),
    otherwise: Yup.string()
  }),
});

And make sure to update your form accordingly. I hope you get the point.

Related