92

我有一个电子邮件字段,只有在选中复选框时才会显示(布尔值为true)。当表单被提交时,如果复选框被选中,我只需要这个字段(布尔值为真)。

这是我迄今为止尝试过的:

    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 得到错误:

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 的验证错误。我究竟做错了什么?

4

7 回答 7

114

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")
      })
  })
}
于 2018-03-26T14:50:24.413 回答
53

Formik作者在这里...

为了使Yup.when工作正常,您必须添加showEmailinitialValues您的 Yup 模式形状。

通常,使用 时validationSchema,最佳实践是确保所有表单的字段都具有初始值,以便 Yup 可以立即看到它们。

结果将如下所示:

<Formik 
  initialValues={{ email: '', showEmail: false }}
  validationSchema={Yup.object().shape({
    showEmail: Yup.boolean(),
    email: Yup
      .string()
      .email()
      .when("showEmail", {
        is: true,
        then: Yup.string().required("Must enter email address")
      })
  })
}

/>
于 2020-08-25T17:44:23.117 回答
21

完全同意@João Cunha 的回答。只是单选按钮用例的补充。

当我们使用单选按钮作为条件时,我们可以检查字符串的值而不是布尔值。例如is: 'Phone'

const ValidationSchema = Yup.object().shape({
  // This is the radio button.
  preferredContact: Yup.string()
    .required('Preferred contact is required.'),
  // This is the input field.
  contactPhone: Yup.string()
    .when('preferredContact', {
      is: 'Phone',
      then: Yup.string()
        .required('Phone number is required.'),
    }),
  // This is another input field.
  contactEmail: Yup.string()
    .when('preferredContact', {
      is: 'Email',
      then: Yup.string()
        .email('Please use a valid email address.')
        .required('Email address is required.'),
    }),

});

这是用 ReactJS 编写的单选按钮,onChange 方法是触发条件检查的关键。

<label>
  <input
    name="preferredContact" type="radio" value="Email"
    checked={this.state.preferredContact == 'Email'}
    onChange={() => this.handleRadioButtonChange('Email', setFieldValue)}
  />
  Email
</label>
<label>
  <input
    name="preferredContact" type="radio" value="Phone"
    checked={this.state.preferredContact == 'Phone'}
    onChange={() => this.handleRadioButtonChange('Phone', setFieldValue)}
  />
  Phone
</label>

这是单选按钮更改时的回调函数。如果我们使用 Formik,setFieldValue是要走的路。

handleRadioButtonChange(value, setFieldValue) {
  this.setState({'preferredContact': value});
  setFieldValue('preferredContact', value);
}
于 2019-07-03T00:45:19.893 回答
14

您甚至可以将函数用于复杂情况。功能案例有助于复杂的验证

validationSchema={yup.object().shape({
    showEmail: yup.boolean(),
    email: yup
      .string()
      .email()
      .when("showEmail", (showEmail) => {
        if(showEmail)
          return yup.string().required("Must enter email address")
      })
  })
}

于 2021-01-06T05:51:17.457 回答
9
email: Yup.string()
    .when(['showEmail', 'anotherField'], {
        is: (showEmail, anotherField) => {
            return (showEmail && anotherField);
        },
        then: Yup.string().required('Must enter email address')
    }),
于 2021-04-23T14:48:03.147 回答
1

我将 yup 与 vee-validate 一起使用

vee验证

这是来自项目的示例代码

const schema = yup.object({
    first_name: yup.string().required().max(45).label('Name'),
    last_name: yup.string().required().max(45).label('Last name'),
    email: yup.string().email().required().max(255).label('Email'),
    self_user: yup.boolean(),
    company_id: yup.number()
        .when('self_user', {
            is: false,
            then: yup.number().required()
        })
})
const { validate, resetForm } = useForm({
    validationSchema: schema,
    initialValues: {
        self_user: true
    }
})

const {
    value: self_user
} = useField('self_user')
const handleSelfUserChange = () => {
    self_user.value = !self_user.value
}
于 2021-09-17T07:38:24.357 回答
1

它非常适合我:

   Yup.object().shape({
    voyageStartDate:Yup.date(),
    voyageEndDate:Yup.date()
        .when(
            'voyageStartDate',
            (voyageStartDate, schema) => (moment(voyageStartDate).isValid() ? schema.min(voyageStartDate) : schema),
        ),
})
于 2021-12-27T06:41:44.857 回答