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()
}),
}),
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()
}),
}),
Share
Improve this question
edited Oct 4, 2021 at 16:39
NearHuscarl
82.1k23 gold badges320 silver badges282 bronze badges
asked Oct 4, 2021 at 11:33
user15973342user15973342
2
- Do you have any error message? – NearHuscarl Commented Oct 4, 2021 at 11:45
- no, I just don't get the validation I require @NearHuscarl – user15973342 Commented Oct 4, 2021 at 11:49
2 Answers
Reset to default 3Try 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"]
]
)
});
Live Demo
This is some kind of duplication, but here are solutions: using .test()
function or create your own Method - .addMethod
.test
function, example here- .addMethod function, example here
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.