Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional validation with Yup and Formik

Here is my validation schema:

const validationSchema = Yup.object().shape({
      person: Yup.object().shape({
        name: Yup.string().required('Field is required'),
        surname: Yup.string().required('Field is required'),
        middleName: Yup.string().required('Field is required'),
        email: Yup.string()
          .email('Wrong e-mail format')
          .required('Field is required')
      }),
      company: Yup.object().shape({
        name: Yup.string().required('Field is required'),
        address: Yup.string().required('Field is required'),
        email: Yup.string()
          .email('Wrong e-mail format')
          .required('Field is required')
      })
    });

And also there are two variables in React State: isPerson and isCompany. How to make validation work conditionally, for example if isPerson is true, then person in validationSchema is required to be validated?

like image 451
Sgt Maddonut Avatar asked Feb 28 '19 05:02

Sgt Maddonut


1 Answers

Updated ans: 2020.

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 61
STEEL Avatar answered Sep 28 '22 16:09

STEEL