In a React application that uses the react-hook-form library, you may want to validate each field within a useFieldArray. The useFieldArray hook provides a way to manage an array of fields, and you can apply validation rules to each one.
Here’s a simple example to demonstrate how to use useFieldArray with validation rules for each field:
Example
-
Install Libraries: Make sure to install react-hook-form if you haven't already.
npm install react-hook-form
-
Form Component: Create a form component that uses useForm and useFieldArray. We'll define some basic validation rules.
import React from 'react';
import { useForm, useFieldArray } from 'react-hook-form';
const DynamicForm = () => {
const { control, handleSubmit, register, formState: { errors } } = useForm({
defaultValues: {
items: [{ name: "", age: "" }] // Default item structure
}
});
const { fields, append, remove } = useFieldArray({
control,
name: "items" // Your field array name
});
const onSubmit = data => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
{fields.map((item, index) => {
return (
<div key={item.id}>
<input
{...register(`items.${index}.name`, { required: "Name is required" })}
placeholder="Name"
/>
{errors.items?.[index]?.name && <p>{errors.items[index].name.message}</p>}
<input
{...register(`items.${index}.age`, {
required: "Age is required",
min: { value: 0, message: "Age must be a positive number" }
})}
placeholder="Age"
type="number"
/>
{errors.items?.[index]?.age && <p>{errors.items[index].age.message}</p>}
<button type="button" onClick={() => remove(index)}>Remove</button>
</div>
);
})}
<button type="button" onClick={() => append({ name: "", age: "" })}>Add Item</button>
<input type="submit" />
</form>
);
};
export default DynamicForm;
Explanation
-
useForm: Initializes the form and sets up validations. defaultValues can be specified to populate the initial fields.
-
useFieldArray: Manages an array of fields. The append method can be used to add new items to the array, while the remove method can be used to delete items.
-
Validation Rules:
- We impose validation rules using the register function:
- The
name field requires a value.
- The
age field requires a positive number and also provides a custom error message if the validation fails.
-
Error Handling: If a field fails validation, an error message is displayed accordingly.
-
Dynamic Input: You can dynamically add or remove inputs from the form.
Conclusion
This example shows how to set up a form with dynamic fields using useFieldArray and validate each field with custom rules using react-hook-form. Adjust the validation rules based on your requirements!