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
Output - Validate dynamic array form in React using React Hook Form - Clue Mediator
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`.
App.js
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 class="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 class="ml10" placeholder="Enter Last Name" {...register(`list.${index}.lastname`)}="">
{errors?.list?.[index]?.lastName && <p>{errors?.list?.[index]?.lastName.message}</p>}
</div>
<div class="btn-box">
{fields.length !== 1 && <button class="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..!! 🙂