Yup: conditional validation schema
18 August 2022 (Updated 26 October 2023)
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
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment