Conditional Validation in Yup

reectrix picture reectrix · Mar 20, 2018 · Viewed 57.7k times · Source

I have an email field that only gets shown if a checkbox is selected (boolean value is true). When the form get submitted, I only what this field to be required if the checkbox is checked (boolean is true).

This is what I've tried so far:

    const validationSchema = yup.object().shape({
       email: yup
             .string()
             .email()
             .label('Email')
             .when('showEmail', {
                 is: true,
                 then: yup.string().required('Must enter email address'),
             }),
        })

I've tried several other variations, but I get errors from Formik and Yup:

Uncaught (in promise) TypeError: Cannot read property 'length' of undefined at yupToFormErrors (formik.es6.js:6198) at formik.es6.js:5933 at <anonymous> yupToFormErrors @ formik.es6.js:6198

And I get validation errors from Yup as well. What am I doing wrong?

Answer

Jo&#227;o Cunha picture João Cunha · Mar 26, 2018

You probably aren't defining a validation rule for the showEmail field.

I've done a CodeSandox to test it out and as soon as I added:

showEmail: yup.boolean()

The form started validation correctly and no error was thrown.

This is the url: https://codesandbox.io/s/74z4px0k8q

And for future this was the correct validation schema:

validationSchema={yup.object().shape({
    showEmail: yup.boolean(),
    email: yup
      .string()
      .email()
      .when("showEmail", {
        is: true,
        then: yup.string().required("Must enter email address")
      })
  })
}