Here is a solution if you need to conditionally validate more than one field against multiple fields. In this example FieldZ
is the only required field. The other three fields A B C
are required only if one of the other two fields is filled in. NOTE: you can add any kind of validation in the is
function. Below I am just checking for the existence of the field value.
export const validationSchema = yup.object().shape({
FieldZ: yup.string().required("Field Z is required"),
// These three fields are All or nothing. If one is selected then they are all required.
FieldA: yup
.string()
.when(['FieldB', 'FieldC'], {
is: (FieldB, FieldC) =>
FieldB || FieldC,
then: yup.string().required('Field A is required')
}),
FieldB: yup
.string()
.when(['FieldA', 'FieldC'], {
is: (FieldA, FieldC) =>
FieldA || FieldC,
then: yup.string().required('Field B is required')
}),
FieldC: yup
.string()
.when(['FieldA', 'FieldB'], {
is: (FieldA, FieldB) =>
FieldA || FieldB,
then: yup.string().required('Field C is required')
}),
},
// Resolve the dependency 'circle'. This tells yup which order to resolve the dependencies
// Failure to do this will result in a yup circular validation error.
[
['FieldA', 'FieldB'],
['FieldA', 'FieldC'],
['FieldB','FieldC' ]
]);