DEV Community

Cover image for Simplifying Form Validation with Zod and React Hook Form
Aadarsh Nagrath
Aadarsh Nagrath

Posted on

Simplifying Form Validation with Zod and React Hook Form

Form validations are crucial in web applications for ensuring data integrity and providing a consistent user experience. In React applications, managing form validations can sometimes be complex and time-consuming. However, by leveraging the power of libraries like React Hook Form and Zod, we can streamline and simplify the process, making it more efficient and developer-friendly.

Introduction

In this article, we will explore how to handle form validations in React using React Hook Form, Zod, and TypeScript. React Hook Form is a lightweight and flexible form library with an intuitive API for managing form state and validations. Zod, on the other hand, is a schema validation library that simplifies the process of defining and validating data structures.

By combining React Hook Form with Zod, we can create robust and reliable form validation systems in React applications. Throughout this article, we will cover key concepts, techniques, and code examples to effectively handle form validations.

Setting Up React Hook Form and Zod

Before we dive into form validations, let's first set up React Hook Form and Zod in our project.

Step 1: Install Dependencies

npm install react-hook-form zod @hookform/resolvers
Enter fullscreen mode Exit fullscreen mode

Step 2: Import Required Components and Hooks

import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
Enter fullscreen mode Exit fullscreen mode

Step 3: Define Form Schema Using Zod

const schema = z.object({
  username: z.string().min(3, { message: 'Username must be at least 3 characters' }),
  email: z.string().min(1, { message: 'Email is required' }).email('Invalid email address'),
  password: z.string().min(6, { message: 'Password must be at least 6 characters' }),
  confirmPassword: z.string().min(6, { message: 'Password must be at least 6 characters' })
});
Enter fullscreen mode Exit fullscreen mode

Step 4: Set Up Form and Validation Resolver

const { register, handleSubmit, formState: { errors } } = useForm<ValidationSchemaType>({
  resolver: zodResolver(schema),
});
Enter fullscreen mode Exit fullscreen mode

Basic Form Validation

Now that we have set up React Hook Form and Zod, let's start with the basics of form validation.

Registering Form Fields

<input type="text" {...register('username')} />
Enter fullscreen mode Exit fullscreen mode

Displaying Error Messages

{errors.username && <span>{errors.username.message}</span>}
Enter fullscreen mode Exit fullscreen mode

Handling Form Submission

const onSubmit: SubmitHandler<ValidationSchemaType> = (data) => {
  console.log(data);
}
Enter fullscreen mode Exit fullscreen mode
<form onSubmit={handleSubmit(onSubmit)}>
  {/* Form fields and error messages */}
</form>
Enter fullscreen mode Exit fullscreen mode

Advanced Form Validation Techniques

Let's explore some advanced techniques for form validation using React Hook Form and Zod.

Cross-Field Validation

const schema = z.object({
  // Other fields...
  confirmPassword: z.string().min(6, { message: 'Password must be at least 6 characters' })
}).refine((data) => data.password === data.confirmPassword, {
  path: ['confirmPassword'],
  message: 'Passwords do not match'
});
Enter fullscreen mode Exit fullscreen mode

Async Validation

const schema = z.object({
  email: z.string().email('Invalid email address').refine(async (value) => {
    // Perform async validation logic
    // Return true if validation passes, false otherwise
  }, 'Email already exists'),
});
Enter fullscreen mode Exit fullscreen mode

Conclusion & Follow Me

Twitter Link
Github Link

Integrating Zod with React Hook Form provides a powerful solution for form validation in React applications. By defining a schema with Zod and using the Zod resolver with React Hook Form, you can easily enforce validation rules and ensure that user inputs meet your specified criteria. This approach simplifies form validation logic, reduces boilerplate code, and improves the overall developer experience when working with forms in React.

Resources:

[Zod Documentation](https://zod.dev/)
[Zod Error Handling](https://zod.dev/ERROR_HANDLING?id=error-handling-in-zod)
[React-Hook-Form Documentation](https://react-hook-form.com/get-started)
[Hookform Resolvers](https://www.npmjs.com/package/@hookform/resolvers)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)