1

I tried to do the validation using yup with react hook form. 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

How to fix this issue

Gmv
  • 2,008
  • 6
  • 29
  • 46
  • Please check this answer [Conditional Validation in Yup](https://stackoverflow.com/questions/49394391/conditional-validation-in-yup) – Safwat Fathi Apr 13 '22 at 09:45

1 Answers1

0

As both h1 and h2 are in the same level of the object, you can use when on the h2.

From yup docs:

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