简体   繁体   English

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

[英]Yup conditional base validation with react hook form

I tried to do the validation using yup with react hook form.我尝试使用 yup 和 react hook 形式进行验证。 When the first checkbox is enabled I want to make the second checkbook required.启用第一个复选框后,我想制作第二个支票簿。 When the second checkbox is enabled remaining fields should be required.启用第二个复选框后,其余字段应为必填字段。

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;
  })

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

How to fix this issue如何解决这个问题

As both h1 and h2 are in the same level of the object, you can use when on the h2 .由于h1h2都在对象的同一级别,因此您可以在h2上使用when

From yup docs :yup 文档

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM