I'm trying to require one of two checkboxes to be selected in a form. The following doesn't seem to work according to the documentation:
yearGroups: yup.object().shape({
primary: yup.bool().when('yearGroups.primary', {
is: false,
then: yup
.bool()
.oneOf([true], '')
.required()
}),
secondary: yup.bool().when('yearGroups.secondary', {
is: false,
then: yup
.bool()
.oneOf([true], '')
.required()
}),
}),
Try this one. See the explanation here:
const schema = yup.object().shape({
yearGroups: yup.object().shape(
{
primary: yup.bool().when("secondary", {
is: (secondary) => !secondary,
then: yup.bool().oneOf([true], "At least one needs to be checked")
}),
secondary: yup.bool().when("primary", {
is: (primary) => !primary,
then: yup.bool().oneOf([true], "At least one needs to be checked")
})
},
[
["primary", "secondary"],
["secondary", "primary"]
]
)
});
This is some kind of duplication, but here are solutions: using .test() function or create your own Method - .addMethod
I am using .addMethod in my code, it's more flexible, you can define all params you need. Once you defined it in the file, you can call it everywhere you need.