Formik and Yup provides a nice easy way to do conditional validation for your React projects.
Using the when
method you can conditionally add validation to a field based on another.
For example, below we want an input required only if a checkbox is checked.
Yup.object().shape({
aCheckbox: Yup.boolean('Select this checkbox please'),
anotherField: Yup.string().when("aCheckbox", {
is: (aCheckbox) => aCheckbox === true,
then: Yup.string().required('I am required now the checkbox is checked')
})
});
Source: Yup documentation
You can even have conditional validation based on an array of fields. In this example, the input is only required if two checkboxes are checked.
Yup.object().shape({
aCheckbox: Yup.boolean('Select this checkbox a please'),
bCheckbox: Yup.boolean('Select this checkbox b please'),
anotherField: Yup.string().when(["aCheckbox", "bCheckbox"], {
is: (aCheckbox, bCheckbox) => aCheckbox === true && bCheckbox === true,
then: Yup.string().required('I am required now that both checkboxes are checked')
})
});