Yup中的条件验证 [英] Conditional Validation in Yup

查看:988
本文介绍了Yup中的条件验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个电子邮件字段,仅在选中复选框(布尔值为true)时才会显示.提交表单后,如果选中此复选框(布尔值为true),则仅此字段是必填字段.

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 if the checkbox is checked (boolean is true).

这是我到目前为止尝试过的:

This is what I've tried so far:

    const validationSchema = yup.object().shape({
       email: yup
             .string()
             .email()
             .label('Email')
             .when('showEmail', {
                 is: true,
                 then: yup.string().required('Must enter email address'),
             }),
        })

我尝试了其他几种变体,但是从Formik和Yup中得到了错误:

I've tried several other variations, but I get errors from Formik and Yup:

Uncaught (in promise) TypeError: Cannot read property 'length' of undefined at yupToFormErrors (formik.es6.js:6198) at formik.es6.js:5933 at <anonymous> yupToFormErrors @ formik.es6.js:6198

Uncaught (in promise) TypeError: Cannot read property 'length' of undefined at yupToFormErrors (formik.es6.js:6198) at formik.es6.js:5933 at <anonymous> yupToFormErrors @ formik.es6.js:6198

我也从Yup收到验证错误.我究竟做错了什么?

And I get validation errors from Yup as well. What am I doing wrong?

推荐答案

您可能没有为 showEmail 字段定义验证规则.

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

我已经添加了CodeSandox来对其进行测试:

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.

这是网址: 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")
      })
  })
}

这篇关于Yup中的条件验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆