Reputation: 33
i need to show validation error when atleast one of the 5 checkboxes is not selected using yup form. i tried by creating schema in this way
const accumulatorsSchema = yup.object().shape({
name: yup.string().required("Name is required"),
a: yup.string(),
b: yup.string(),
c: yup.string(),
d: yup.string(),
e: yup.string(),
checkbox_selection: yup.string().when(["a","b", "c","d", "e"], {
is: (a, b, c, d, e) => !a && !b && !c && !d && !e,
then: yup.string().required("At least one checkbox is to be selected"),
otherwise: yup.string()
})
})
here in the above code a,b,c,d,e are five checkboxes where i am going to save "Y" on checked and "N" on unchecked. if atleast one of them is not checked then i need to show a required validation error. i couldn't find a way to fix it. can anyone help me? Thanks in advance.
Upvotes: 0
Views: 4283
Reputation: 1714
I've tested your schema, it works, the logic is fine.
Reproduced
codesandbox.io/s/yup-playground-forked-krlqy?file=/src/index.js
import { object, string } from "yup";
const schema = object().shape({
name: string().required("Name is required"),
a: string(),
b: string(),
c: string(),
d: string(),
e: string(),
checkbox_selection: string().when(["a", "b", "c", "d", "e"], {
is: (a, b, c, d, e) => !a && !b && !c && !d && !e,
then: string().required("At least one checkbox is to be selected"),
otherwise: string() // unnecessary
})
});
schema
// .validate({ name: "foo" }) // ValidationError: At least one checkbox is to be selected
.validate({ name: "foo", a: 'foo' }) // Ok
.then((res) => {
console.log(res);
})
.catch((e) => {
console.log(e);
});
Upvotes: 0