Проверка динамически созданного поля с использованием Formik Yup - PullRequest
0 голосов
/ 09 апреля 2020

Мне нужно проверить динамически созданные поля с помощью formik или yup. Я видел эту проверку в jquery validatioh здесь

like this до this to this

Мой код здесь https://codesandbox.io/s/hidden-haze-47k73?file= / src / demo. js

Как мне добиться этого с помощью formik и да

1 Ответ

0 голосов
/ 09 апреля 2020

Если вы используете 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>
  ))
 }}

Вы можете найти полностью готовый код здесь

...