【问题标题】:Validation Dynamically created Field using Formik Yup使用 Formik Yup 验证动态创建的字段
【发布时间】:2020-07-21 16:39:52
【问题描述】:

我需要使用 formik 或 yup 验证动态创建的字段。我已经看到在 jquery validatioh here 中完成了此验证

给这个

我的代码在这里 https://codesandbox.io/s/hidden-haze-47k73?file=/src/demo.js

我如何使用 formik 和 yup 实现这一目标

【问题讨论】:

  • 您能解释一下您如何动态创建字段吗? FieldArray 还是什么?你能显示它的最低代码吗?
  • 请稍等我会更新
  • 我已经更新了我的代码链接。我正在处理你的答案

标签: formik yup


【解决方案1】:

如果您使用formik FieldArray。你可以用yup查看它的字段:

firends: Yup.array().of(
    Yup.object().shape({
       name: Yup.string().required('Name is required'),
       email: Yup.string()
                .email("Invalid email")
                .required('Email is required'),
    })
),

您的FieldArray 将是:

<FieldArray                                                          
 name="firends"
 render={(arrayHelpers) => {
  {values.firends && values.firends.length > 0 ? (
     values.firends.map((friend, index) => (
    <div key={index}>
      <Field
         className="form-control"
         name={`friends.${index}.name`}
         placeholder="name"
         type="text"
      />
        {errors &&
         errors.friends &&
         errors.friends[index] &&
         errors.friends[index].name &&
           (touched &&
            touched.friends &&
            touched.friends[index] &&
            touched.friends[index].name) && (
              <div className="field-error">
                {errors.friends[index].name}
              </div>
      )}
     <Field
         className="form-control"
         name={`friends.${index}.email`}
         placeholder="email"
         type="text"
      />
        {errors &&
         errors.friends &&
         errors.friends[index] &&
         errors.friends[index].email &&
           (touched &&
            touched.friends &&
            touched.friends[index] &&
            touched.friends[index].email) && (
              <div className="field-error">
                {errors.friends[index].email}
              </div>
      )}
  </div>
  ))
 }}

您可以找到完全准备好的代码here

【讨论】:

  • 您好验证有效,但添加新字段时我失去了焦点,任何方式都可以在提交时关注空字段
猜你喜欢
  • 2019-09-29
  • 1970-01-01
  • 2021-06-27
  • 2021-12-31
  • 1970-01-01
  • 2019-10-05
  • 1970-01-01
  • 2022-12-19
  • 2020-05-10
相关资源
最近更新 更多