2

I'm trying to require one of two checkboxes to be selected in a form. The following doesn't seem to work according to the documentation:

yearGroups: yup.object().shape({
          primary: yup.bool().when('yearGroups.primary', {
            is: false,
            then: yup
              .bool()
              .oneOf([true], '')
              .required()
          }),
          secondary: yup.bool().when('yearGroups.secondary', {
            is: false,
            then: yup
              .bool()
              .oneOf([true], '')
              .required()
          }),
        }),
NearHuscarl
  • 66,950
  • 18
  • 261
  • 230

2 Answers2

3

Try this one. See the explanation here:

const schema = yup.object().shape({
  yearGroups: yup.object().shape(
    {
      primary: yup.bool().when("secondary", {
        is: (secondary) => !secondary,
        then: yup.bool().oneOf([true], "At least one needs to be checked")
      }),
      secondary: yup.bool().when("primary", {
        is: (primary) => !primary,
        then: yup.bool().oneOf([true], "At least one needs to be checked")
      })
    },
    [
      ["primary", "secondary"],
      ["secondary", "primary"]
    ]
  )
});

Live Demo

Codesandbox Demo

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
0

This is some kind of duplication, but here are solutions: using .test() function or create your own Method - .addMethod

  1. .test function, example here
  2. .addMethod function, example here

I am using .addMethod in my code, it's more flexible, you can define all params you need. Once you defined it in the file, you can call it everywhere you need.

illia chill
  • 1,652
  • 7
  • 11