Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

171
Views
Validation using Yup with key

So I'm trying to validate my form using the Yup package, there is a function createForm to create a form which creates a form with unique ID, and then that ID is pass to fields for every form which is created. I'm trying to validate those fields for each form created but I'm failing to validate those inputs with the unique id present. Here is the code :

import { nanoid } from 'nanoid';

const AddContact = () => {
  const [formData, setFormData] = useState([{key: nanoid()}])

    const createForm = () => {
      setFormData(prevFormData => [...prevFormData, {key: nanoid()}])
    }

   const deleteForm = (key) => {
      setFormData(prevFormData => prevFormData.filter(item => item.key !== key))
    }

return(
<Formik
      initialValues={{}}
      validationSchema={
      formData.map(data => {
         Yup.object().shape({
           [`name_${data.key}`]: Yup.string().required("Please enter a valid name"),
           [`company_${data.key}`]: Yup.string().required("Please enter a Company name"),
           [`mobile_no_${data.key}`]: Yup.number().typeError("Please enter a valid mobile number"),
           [`email_${data.key}`]: Yup.string().email().required("Please enter a valid email"),
         })
       })
     }
       //onSubmit={onSubmit}
>
 {({ handleSubmit, values }) => {
       return(
            <div>
              {formData.map((data, index) => {
               return(
               <button onClick={() => deleteForm(data.key)}}>
               <input name={`name_${data.key}`}>
               <input name={`company_${data.key}`}>
               <input name={`mobile_no_${data.key}`}>
               <input name={`email_${data.key}`}>
              )})}
              <button onClick={createForm}/>
            </div>
     )
}}


about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Try this code: I have created validationSchema from formData and it is working fine as it shows errors and values at the bottom of the form right now.

import React, { useState } from "react";
import { Formik } from "formik";
import { nanoid } from "nanoid";
import * as Yup from "yup";

const AddContact = () => {
  const [formData, setFormData] = useState([{ key: nanoid() }]);

  const createForm = () => {
    setFormData((prevFormData) => [...prevFormData, { key: nanoid() }]);
  };

  const deleteForm = (key) => {
    setFormData((prevFormData) =>
      prevFormData.filter((item) => item.key !== key)
    );
  };

  const validationSchema = {
    ...formData.reduce((result, data) => {
      result = {
        ...result,
        [`name_${data.key}`]: Yup.string().required(
          "Please enter a valid name"
        ),
        [`company_${data.key}`]: Yup.string().required(
          "Please enter a Company name"
        ),
        [`mobile_no_${data.key}`]: Yup.number().typeError(
          "Please enter a valid mobile number"
        ),
        [`email_${data.key}`]: Yup.string()
          .email()
          .required("Please enter a valid email")
      };
      return result;
    }, {})
  };

  return (
    <Formik
      initialValues={{}}
      validationSchema={Yup.object().shape(validationSchema)}
    >
      {({ handleSubmit, values, errors, handleChange }) => {
        return (
          <div>
            {formData.map((data, index) => (
              <div key={index} style={{ margin: 10 }}>
                <button onClick={() => deleteForm(data.key)}>Delete</button>
                <input name={`name_${data.key}`} onChange={handleChange} />
                <input name={`company_${data.key}`} onChange={handleChange} />
                <input name={`mobile_no_${data.key}`} onChange={handleChange} />
                <input name={`email_${data.key}`} onChange={handleChange} />
              </div>
            ))}
            <button onClick={createForm} style={{ margin: 10 }}>
              Create Form
            </button>
            <button type="submit" onClick={handleSubmit}>
              Submit
            </button>
            {errors && (
              <div>
                <div>ERRORS: {JSON.stringify(errors)}</div>
                <div>VALUES: {JSON.stringify(values)}</div>
              </div>
            )}
          </div>
        );
      }}
    </Formik>
  );
};

export default AddContact;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!