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

时间:2021-06-30 08:12:10

标签: javascript reactjs yup react-hook-form

我尝试使用 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

如何解决这个问题

1 个答案:

答案 0 :(得分:0)

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

来自yup docs

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