Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Yup validation according to state variable

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

like image 370
Alan Shajan Mattathil Avatar asked Aug 08 '26 09:08

Alan Shajan Mattathil


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.

like image 91
Asif vora Avatar answered Aug 09 '26 21:08

Asif vora