Validate dynamic array form in React using React Hook Form
Today, we’ll show you how to validate a dynamic array form in React using React Hook Form. Refer to the following article, if you don’t know how to create a simple form in React using react-hook-form.
Demo Application
Validate dynamic array form using React Hook Form
1. Create a dynamic form using useFieldArray
If you are new to React Hook Form then I will recommend you to check out these articles on React Hook Form.
In this example, we will continue the previous example so please refer to the previous article for more information.
Dynamic form with React Hook Form using useFieldArray
2. Add validation for an array fields
To add validation, you need to install the @hookform/resolvers
and yup
packages. Refer to the following article for simple form validation.
Validate a form in React using react-hook-form
Basic steps to add validation to an array field.
- Create a schema for the list.
- Attach the schema to form.
- Finally, read the error message from the error list like
errors?.list?.[index]?.firstName.message
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | import React, { useState } from 'react'; import { useForm, useFieldArray } from 'react-hook-form'; import { yupResolver } from '@hookform/resolvers/yup'; import * as yup from "yup"; const schema = yup.object().shape({ list: yup.array().of( yup.object().shape({ firstName: yup.string().required("First Name is required"), lastName: yup.string().required("Last Name is required") }) ) }); const App = () => { const [data, setData] = useState(); const { control, register, handleSubmit, formState: { errors } } = useForm({ defaultValues: { list: [{ firstName: '', lastName: '' }] }, resolver: yupResolver(schema) }); const { fields, append, remove } = useFieldArray({ control, name: "list" }); const onSave = data => { setData({ ...data }); } return <form onSubmit={handleSubmit(onSave)}> <h4>Validate dynamic array form in React using React Hook Form - <a href="https://www.cluemediator.com/" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h4> {fields.map((field, index) => ( <div className="box" key={field.id}> <div> <input placeholder="Enter First Name" {...register(`list.${index}.firstName`)} /> {errors?.list?.[index]?.firstName && <p>{errors?.list?.[index]?.firstName.message}</p>} </div> <div> <input className="ml10" placeholder="Enter Last Name" {...register(`list.${index}.lastName`)} /> {errors?.list?.[index]?.lastName && <p>{errors?.list?.[index]?.lastName.message}</p>} </div> <div className="btn-box"> {fields.length !== 1 && <button className="mr10" onClick={() => remove(index)}>Remove</button>} {fields.length - 1 === index && <button onClick={() => append({ firstName: '', lastName: '' })}>Add</button>} </div> </div> ))} <button>Submit</button> {data && <pre>{JSON.stringify(data, null, 2)}</pre>} </form> } export default App; |
3. Output
Run the application and check the output in the browser.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂