最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Yup validation requiring at least one selection - Stack Overflow

programmeradmin3浏览0评论

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()
          }),
        }),

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()
          }),
        }),
Share Improve this question edited Oct 4, 2021 at 16:39 NearHuscarl 82.1k23 gold badges320 silver badges282 bronze badges asked Oct 4, 2021 at 11:33 user15973342user15973342 2
  • Do you have any error message? – NearHuscarl Commented Oct 4, 2021 at 11:45
  • no, I just don't get the validation I require @NearHuscarl – user15973342 Commented Oct 4, 2021 at 11:49
Add a ment  | 

2 Answers 2

Reset to default 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

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.

发布评论

评论列表(0)

  1. 暂无评论