是的,带有反应钩子形式的条件基础验证

问题描述

我尝试使用 yup 和 react hook 形式进行验证。启用第一个复选框后,我想制作第二个支票簿。启用第二个复选框后,其余字段应为必填字段。

yup.object().shape({
  firstName: yup.string().required(),age: yup.number().required().positive().integer(),website: yup.string().url(),h1: yup.boolean(),h2: yup.boolean().test("required","h2 required",function validator(val) {
    const { h1 } = this.parent;
    return h1;
  })

我的代码和框链接https://codesandbox.io/s/react-hook-form-validationschema-forked-pmcgo?file=/src/index.js:178-471

如何解决这个问题

解决方法

由于 h1h2 都在对象的同一级别,因此您可以在 when 上使用 h2

来自yup docs

let schema = object({
  foo: array().of(
    object({
      loose: boolean(),bar: string().when('loose',{
        is: true,otherwise: (s) => s.strict(),}),),});

相关问答

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