While using yup, there might be a scenario where you might have to make one field required if another field has a certain value (say if the other field is empty).
For example, consider the following scenario:
You have 3 fields in a form: is_mobile_app
, ios_id
and android_id
. If is_mobile_app
is false, then both ios_id
and android_id
both are optional. But if is_mobile_app
is true, then you must have to fill in either ios_id
or android_id
, i.e., ios_id
is required if android_id
is null and vice versa.
In order to achieve that, you have to write the following code. This code addresses the above issue and also will not throw the cyclic dependency error:
export const MobileAppSchema = yup.object().shape(
{
is_mobile_app: yup.boolean().required(),
ios_id: yup.string().when(["android_id", "is_mobile_app"], {
is: (android_id: string, is_mobile_app: boolean) => is_mobile_app === true && !android_id,
then: yup.string().required(),
otherwise: yup.string().optional().nullable(),
}),
android_id: yup.string().when(["ios_id", "is_mobile_app"], {
is: (ios_id: string, is_mobile_app: boolean) => is_mobile_app === true && !ios_id,
then: yup.string().required(),
otherwise: yup.string().optional().nullable(),
}),
},
[
["ios_id", "is_mobile_app"],
["android_id", "is_mobile_app"],
["ios_id", "android_id"],
]
);
Using the code above, you can handle any kind of conditional logic in yup to validate individual fields which depend on the input of other fields. This can come pretty handy if you are also using Formik forms in conjunction with yup.
References:
https://github.com/jquense/yup/issues/176
https://github.com/jquense/yup/issues/193
https://github.com/jquense/yup/issues/79
https://stackoverflow.com/questions/49394391/conditional-validation-in-yup