Dev
Dev

Reputation: 189

Validation Dynamically created Field using Formik Yup

I need to validate Dynamically created fields with formik or yup .I have seen this validation done by in jquery validatioh here

like this to this to this

My code in here https://codesandbox.io/s/hidden-haze-47k73?file=/src/demo.js

How do i achieve this using formik and yup

Upvotes: 4

Views: 8878

Answers (1)

aturan23
aturan23

Reputation: 5410

If you using formik FieldArray. You can check it's fields with 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'),
    })
),

And your FieldArray will be:

<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>
  ))
 }}

You can find fully ready code here

Upvotes: 6

Related Questions