【问题标题】:Formik + Yup don't validate input if untouched如果未触及,Formik + Yup 不验证输入
【发布时间】:2019-11-12 14:49:14
【问题描述】:

我正在尝试使用 Formik + Yup 来验证我的表单,但目前如果我触摸一个字段,然后尝试提交,则会验证一个具有最小长度的字段,并且不允许我提交。

按照我的代码沙箱 (https://codesandbox.io/s/focused-bardeen-5fiuz),我希望用户能够提交表单,如果他们只是更改 firstName 字段,但不为 country 字段输入任何内容。我尝试了.notRequired() 和.nullable(true) 参数,但没有奏效。知道如何实现这一目标吗?

【问题讨论】:

    标签: node.js reactjs formik yup


    【解决方案1】:

    您可以尝试对test 使用自定义验证。这里是一个工作示例https://codesandbox.io/s/laughing-dust-f9wet

    country: yup
          .string()
          .test("isValidCode", "Country must be 2-letters (ISO codes).", value => {
            if (!value) {
              return true;
            }
            return value.toString().length === 2;
          })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-09
      • 2019-09-29
      • 2022-01-17
      • 2020-12-06
      • 1970-01-01
      • 1970-01-01
      • 2020-08-06
      • 2020-01-01
      相关资源
      最近更新 更多