DEV Community

Aashutosh Poudel
Aashutosh Poudel

Posted on

28 2

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay