如何使用Yup和Formik验证表单

时间:2020-01-17 16:41:21

标签: reactjs formik yup

我需要验证复选框是否在DOM中。

这是我的验证架构。因此,根据某些状态是对还是错,我将显示confirm1或confirm2复选框。当前字段没有显示错误,我无法提交表格。

 const validationSchema = yup.object().shape({
    confirm1: yup.boolean().notRequired()
    .when('confirm2', {
      is: (val) => val === true,
      then: yup.boolean().required('Field must be checked'),
      otherwise: yup.boolean().notRequired()
    }),
    confirm2: yup.boolean().notRequired()
    .when('confirm1', {
      is: (val) => val === true,
      then: yup.boolean().required('Field must be checked'),
      otherwise: yup.boolean().notRequired()
    })
  }, ['confirm1', 'confirm2'])

1 个答案:

答案 0 :(得分:0)

所以我找到了解决方案,我只是像这样更改了它,并且按预期工作了

confirm1: yup.boolean().notRequired()
  .when('confirm2', {
     is: (val) => val !== true,
     then: yup.boolean().oneOf([true], 'Field must be checked'),
     otherwise: yup.boolean().required()
  }),
confirm1: yup.boolean().notRequired()
    .when('confirm2', {
      is: (val) => val !== true,
      then: yup.boolean().oneOf([true], 'Field must be checked'),
      otherwise: yup.boolean().required()
    }),