sajad torkamani

Use completely different schemas based on condition

const withoutEmailSchema = yup.object().shape({
  firstName: yup.string().required(),
  lastName: yup.string().required(),
})

const withEmailSchema = withoutEmailSchema.shape({
  email: yup.string().required().email(),
})

const validationSchema = someBoolCondition
  ? withoutEmailSchema
  : withEmailSchema

// Do something with the validationSchema (e.g., pass it to Formik)

Use the when helper to conditionally build the schema

  const validationSchema = yup.object().shape({
    [RegisterInputFields.favouriteLanguage]: yup
      .string()
      .when(RegisterInput.profession, {
        is: 'programmer',
        then: yup.string().required(),
      })
  })

Sources

Tagged: Yup