问题描述
当使用 yup 表单未选择 5 个复选框中的至少一个时,我需要显示验证错误。 我尝试通过这种方式创建架构
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()
})
})
在上面的代码中,a、b、c、d、e 是五个复选框,我将在其中将“Y”保存在选中状态,将“N”保存在未选中状态。如果至少其中一个没有被检查,那么我需要显示一个必需的验证错误。我找不到修复它的方法。谁能帮我?提前致谢。
解决方法
我已经测试了你的架构,它有效,逻辑很好。
转载
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);
});