DEV Community

Aashutosh Poudel
Aashutosh Poudel

Posted on

Conditional validation of form fields using Yup

I had a form where I needed to enter the passphrase if it was required and make it optional if it wasn't required. While validating the field using Yup I needed a way to conditionally change the validation logic for the field. For this, we need to use the when() function from Yup which allows us to change the validation logic applied to a field based on some conditions.

Sample code:

<Formik
      initialValues={initialValues}
      validationSchema={Yup.object({
        passphrase: Yup.string().when([], {
          is: () => passwordRequired && !showMessage,
          then: Yup.string().required("Passphrase is required"),
          otherwise: Yup.string().notRequired(),
        }),
      })}
>
  {/* ... */}
</Formik>
Enter fullscreen mode Exit fullscreen mode

References:

  1. Yup docs on when() function
  2. SO post with good answers

Top comments (1)

Collapse
 
carlosspohr profile image
Carlos Spohr

Thank you!

I was searching for a way to create schema based in user configuration for required fields in a form.