【问题标题】:How to validate a non required filed with yup如何使用 yup 验证非必填字段
【发布时间】:2019-07-11 19:27:41
【问题描述】:

我正在使用 yup 和 formik 进行验证。我想用是的来验证一个非必填字段。这里 test 是一个非必填字段,但是当用户输入时,我们会阻止他输入一些特殊字符。当用户没有输入任何内容时,它也在验证(在用户输入内容之前我不需要此验证)。谁能帮帮我,提前谢谢

   const validationSchema = function (values) {
    return Yup.object().shape({
       test: Yup.string()
      .matches(/^[^<&>`#]+$/,'test should not contain `, &, #, <, > \n')
    })
  }

【问题讨论】:

    标签: reactjs validation formik yup


    【解决方案1】:

    errors.yourFieldNametouched.yourFieldName 的组合解决了您的问题:

    因此,如果您的输入字段的名称是 test 以显示/隐藏错误:

    {errors.test && touched.test ? {errors.test}: 'Valid form'}
    

    并启用/禁用您的提交按钮:

    <button disabled={touched.test && (!isValid || isSubmitting)}>
    

    我在这里创建了一个简单的演示 https://codesandbox.io/s/q8vz32mpw

    【讨论】:

    • 嗨@Ala Eddine JEBALI,感谢您的回复。我刚刚尝试了您在字段数组验证中的步骤,但仍然收到相同的错误(可能缺少某些内容)。我创建了一个演示来说明我的问题codesandbox.io/s/6x3yj3kjlw
    • 这是因为您在 const Values = { founded_by: [], } 中将 founded_by 声明为数组,但您使用 Yup founded_by: Yup.string().matches(...) 将其验证为字符串
    • 因此,对于该字段,您应该像这样更改它:const Values = { founded_by: "", founders: ... }
    • 创始人呢?
    • 这与您的问题无关,因为您将它们标记为required:&lt;Input type="text" name={`founders[${index}].linkedinLink`} required ... /&gt;
    猜你喜欢
    • 2019-07-09
    • 2021-12-05
    • 2012-05-23
    • 2021-06-14
    • 2013-08-05
    • 2019-09-29
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    相关资源
    最近更新 更多