Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation Dynamically created Field using Formik Yup

Tags:

yup

formik

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

like image 425
Dev Avatar asked Oct 23 '25 02:10

Dev


1 Answers

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

like image 135
aturan23 Avatar answered Oct 27 '25 04:10

aturan23



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!