React Hook Form is a popular library for handling form validation in React. It’s lightweight, flexible, and works seamlessly with various validation libraries, including Zod. Zod is a schema-based validation library that makes it easy to define and validate data.
In this article, we’ll learn how to use React Hook Form with Zod resolvers to create a simple and powerful form validation setup.
Step 1: Install Required Libraries
First, let’s install the necessary libraries:
npm install react-hook-form zod @hookform/resolvers
Here’s what each package does:
- react-hook-form: The main library for managing forms.
- zod: For schema-based validation.
- **@hookform/**resolvers: Connects React Hook Form with Zod or other validation libraries.
Step 2: Create a Simple Form
We’ll build a form to collect a user’s name and email, validating these fields using Zod.
Import Required Modules
Start by importing the necessary modules:
import React from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
Define the Validation Schema
Using Zod, define a schema for form validation:
const schema = z.object({
name: z.string().min(1, 'Name is required'),
email: z.string().email('Invalid email address'),
});
name
: Must be a non-empty string.email
: Must be a valid email address.
Set Up the Form
Now, use useForm
to set up the form with React Hook Form and Zod:
function App() {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: zodResolver(schema),
});
const onSubmit = (data) => {
console.log('Form Data:', data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label htmlFor="name">Name:</label>
<input id="name" {...register('name')} />
{errors.name && <p>{errors.name.message}</p>}
</div>
<div>
<label htmlFor="email">Email:</label>
<input id="email" {...register('email')} />
{errors.email && <p>{errors.email.message}</p>}
</div>
<button type="submit">Submit</button>
</form>
);
}
export default App;
Explanation
register
: Connects the input fields to React Hook Form.handleSubmit
: Handles the form submission logic.errors
: Contains validation error messages returned by Zod.resolver
: Uses Zod as the validation library viazodResolver
.
Error Handling
The errors
object contains validation errors for each field. We display the error message below each input field using:
{errors.name && <p>{errors.name.message}</p>}
This ensures users know what’s wrong with their input.
Step 3: Test the Form
Run your app and try submitting the form:
- Leave the fields empty to see validation messages.
- Enter invalid email addresses to test email validation.
- Fill in valid data to submit successfully.
Conclusion
By combining React Hook Form with Zod, you can create powerful, flexible, and type-safe form validation in React. This setup is easy to use and scalable for larger applications.
Try building more complex forms by adding more fields and validation rules with Zod!