【问题标题】:Formik's "isValid" reporting true even though validation schema reports an error即使验证模式报告错误,Formik 的“isValid”也报告为真
【发布时间】:2020-09-08 12:06:28
【问题描述】:

在某些情况下,Formik 的标志“isValid”似乎设置为true,即使表单值不应被视为有效。我在下面展示了一个工作代码框示例。

https://m229l.csb.app/

我用于表单的验证架构如下:

const validationSchema = Yup.object().shape(
  {
    heading: Yup.string().required('Heading required.'),
    image: Yup.string().when('placeholder', {
      is: '',
      then: Yup.string().required(
        'Please either choose an image, or a placeholder.'
      ),
      otherwise: Yup.string(),
    }),
    placeholder: Yup.string().when('image', {
      is: '',
      then: Yup.string().required(
        'Please either choose an image, or a placeholder.'
      ),
      otherwise: Yup.string(),
    }),
  },
  [['image', 'placeholder']]
);

当输出 Formik 的 isValid 标志时,它是 true 用于以下值:

{ heading: 'a', image: '', placeholder: '' }

架构规定其中一个字段“图像”或“占位符”必须存在,但在上述情况下,它们不是。然而isValid 标志是true

当使用 Yup 手动测试时,我得到了预期的结果:

validationSchema.validate(values).then(...).catch(...);

这可以在代码框中进一步看到。我在这里想念什么?当 Formik 验证值时,幕后是否发生了更多事情?

【问题讨论】:

    标签: reactjs formik yup


    【解决方案1】:

    我也遇到了同样的问题,因此与formik.isValid 一起,我使用了另一个属性formik.touched 并且仅当formik.isValid = true 时才认为表单是有效Object.keys(formik.touched).length > 0(至少应该触摸一些字段)如下:

    const isFormValid = formik.isValid && Object.keys(formik.touched).length > 0; // WITH lodash: formik.isValid && !_.isEmpty(formik.touched)
    if (isFormValid) {
     // NOW SUBMIT THE FORM OR DO YOUR NEXT STEP
    }
    

    【讨论】:

      猜你喜欢
      • 2013-05-12
      • 2015-08-09
      • 2020-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多