当其他字段为空时显示 yup 字段验证至少一个字段必须是有效的

问题描述

当使用 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);
    });

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...