Conditional Validation in Yup

后端 未结 3 726
刺人心
刺人心 2020-12-29 01:28

I have an email field that only gets shown if a checkbox is selected (boolean value is true). When the form get submitted, I only what this field to be required

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-29 02:19

    You probably aren't defining a validation rule for the showEmail field.

    I've done a CodeSandox to test it out and as soon as I added:

    showEmail: yup.boolean()
    

    The form started validation correctly and no error was thrown.

    This is the url: https://codesandbox.io/s/74z4px0k8q

    And for future this was the correct validation schema:

    validationSchema={yup.object().shape({
        showEmail: yup.boolean(),
        email: yup
          .string()
          .email()
          .when("showEmail", {
            is: true,
            then: yup.string().required("Must enter email address")
          })
      })
    }
    

提交回复
热议问题