首页 > 解决方案 > 使用 Formik Yup 验证动态创建的字段

问题描述

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

像这样对此对此

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

我如何使用 formik 和 yup 来实现这一点

标签: formikyup

解决方案


如果您使用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>
  ))
 }}

你可以在这里找到完全准备好的代码


推荐阅读