Skip to content
Advertisement

Yup conditional validation depending on if another field is valid?

I’m working on a project with a long registration form made with MUI, react-hook-forms and yup. There would be one field rendered at a time with a “Next” button to change the displayed input field to a next one (i.e. go from email field to name field). Right now it doesn’t let me submit the email field and display the name field because it wants to validate both since there is no conditional validation. I have a following schema:

const schema = yup.object().shape({
  email: yup.string().email().required(),
  firstName: yup.string().required("Please enter your first name"),
});

From what I’ve read online I understand that I need to use the .when method for the firstName field, except I don’t know how to make it check based on if the email field is valid. I have tried the following:

const schema = yup.object().shape({
  email: yup.string().email().required(),
  firstName: yup.string().when("email", {
    is: (value) => value !== undefined,
    then: yup.string().required("Please enter your first name"),
    otherwise: yup.string().notRequired(),
  }),
});

But the value is defined onChange so it doesn’t work.

Advertisement

Answer

I figured it out. I have divided the main schema into an emailSchema and a nameSchema, and then I used the concat method based on the step of the registration (1 being the step with the frist name field).

const schema = step === 1 ? emailSchema.concat(nameSchema) : emailSchema
Advertisement