React Hook Form with Zod for Form Validation with ease

React Hook Form with Zod for Form Validation with ease. Building forms in React can often be a tedious task, especially when dealing with complex validation rules and managing form state. Fortunately, libraries like React Hook Form simplify this process significantly.

React Hook Form with Zod - 2025
React Hook Form with Zod – 2025

When combined with a schema validation library like Zod and its dedicated Zod Resolver, you can create robust, type-safe, and highly efficient forms with minimal boilerplate. This blog will guide you through the process of integrating React Hook Form with Zod and Zod Resolver to handle form submission and validation effectively.

React এ ফর্ম তৈরি করা একটা জটিল কাজ, বিশেষ করে যখন ফর্ম এ অনেক বেশি Input Field থাকে, আর কিছু complex validation rules থাকে। এইসব ক্ষেত্রে useState ব্যবহার করে state management করা অনেক কঠিন হয়ে পরে। ঠিক সেই সময় react-hook-form এর মোট library এর প্রসেস টাকে সহজ করে ফেলে আমাদের জন্য। আর যখন আমরা এটাকে zod এবং zodResolver এর সাথে সংযুক্ত করে ফেলি তখন কাজ টা হয়ে যায় আরও সহজ, আমরা শুধুমাত্র একটা schema তৈরি করার মাধ্যমেই সহজে ফর্ম validate করে ফেলতে পরি, আমাদের কোন complex লজিক আর লিখতে হয় না।

Why React Hook Form, Zod, and Zod Resolver?

let’s understand why this combination is so powerful for form validation and form state management.

  • React Hook Form: This library offers a user friendly approach to form management, works by using uncontrolled components and reducing re-renders. It provides simple functions for registering inputs, handling submissions, and displaying errors. For more details, visit the official React Hook Form documentation.
  • Zod: Zod is a schema declaration and validation library. It allows us to define schemas for our data strcture, ensuring type safety and provides powerful validation capabilities. All we have to do is create a schema based on our data and zod will handle the rest of the validtion logic.
  • Zod Resolver: This package acts as a bridge between React Hook Form and Zod. It makes react-hook-form understand the schema and enforce the validation logic into its input fields.

By combining these 3 things we are ensuring type-safety, less rerender and improved performance.

Setting Up Your Project

To get started with React Hook Form, Zod, and Zod Resolver, you’ll need to install the necessary packages. Run the follwing command to install all the required libraries.

npm install react-hook-form zod @hookform/resolvers
# or
yarn add react-hook-form zod @hookform/resolvers

Defining Your Zod Schema for Form Validation

First we have to create the schema using zod according to our form. Since we are building a Contact Form, we will have 3 input fields, Name , Email , and Message

import { z } from 'zod';

export const contactFormSchema = z.object({
  name: z.string().min(3, 'Name must be at least 3 characters').max(50, 'Name cannot exceed 50 characters'),
  email: z.string().email('Invalid email address'),
  message: z.string().min(10, 'Message must be at least 10 characters'),
});

In this schema:

  • z.object defines an object shape for our form data.
  • z.string() indicates that the field should be a string.
  • .min() and .max() are used for length validation.
  • .email() specifically validates an email format.

Now the schema is ready to be used with react-hook-form and zod resolver to automatically validate our form fields.

Building Your Form with React Hook Form and Zod Resolver

Now, let’s create a React component that uses React Hook Form and the Zod Resolver to handle our contact form.

import React from 'react';
import { z } from 'zod'
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';

const contactFormSchema = z.object({
  name: z.string()
					  .min(3, 'Name must be at least 3 characters')
					  .max(50, 'Name cannot exceed 50 characters'),
  email: z.string().email('Invalid email address'),
  message: z.string().min(10, 'Message must be at least 10 characters'),
});

const ContactForm = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(contactFormSchema),
  });

  const onSubmit = (data) => {
    console.log('Form data submitted:', data);
    // Now do whatever you want to do with the data
  };

  return (
    <div>
      <h2>Contact Us</h2>
      <form onSubmit={handleSubmit(onSubmit)}>
        <div>
          <label htmlFor="name">Name:</label>
          <input
            id="name"
            type="text"
            {...register('name')}
          />
          {errors.name && <p className="text-red-500">{errors.name.message}</p>}
        </div>

        <div>
          <label htmlFor="email">Email:</label>
          <input
            id="email"
            type="email"
            {...register('email')}
          />
          {errors.email && <p className="text-red-500">{errors.email.message}</p>}
        </div>

        <div>
          <label htmlFor="message">Message:</label>
          <textarea
            id="message"
            {...register('message')}
          ></textarea>
          {errors.message && <p className="text-red-500">{errors.message.message}</p>}
        </div>

        <button type="submit">
          Submit
        </button>
      </form>
    </div>
  );
  
};

export default ContactForm;

Here’s a breakdown of the key parts of this component for form submission and validation:

  • useForm({ resolver: zodResolver(contactFormSchema) }): This is where we initialize React Hook Form. We pass zodResolver(contactFormSchema) to the resolver option. This tells React Hook Form to use our Zod schema for validation.
  • register('fieldName'): This function is used to register your input fields with React Hook Form. It automatically handles input value tracking and validation.
  • handleSubmit(onSubmit): This function from useForm wraps your onSubmit handler. It will only call onSubmit if the form passes all the form validation rules defined in your Zod schema.
  • formState: { errors }: The errors object contains any validation errors. If a field has an error, errors.fieldName.message will contain the corresponding error message from your Zod schema.

Complete web development with Programming Hero

-৪৩০০+ জব প্লেসমেন্ট
– ৩ বেলা ডেডিকেটেড লাইভ সাপোর্ট
-১০০% জব প্লেসমেন্ট সাপোর্ট
-৮৫ টি মডিউল, ১২+ মাইলস্টোন
-ডেডিকেটেড হেল্প ডেস্ক ২৪/৭

Displaying Validation Errors

One of the most important aspects of form validation is providing clear feedback to the user when errors occur. As shown in the example above, we access the errors object from formState.

{errors.name && <p>{errors.name.message}</p>}

This snippet checks if there’s an error for the name field and, if so, displays the error message provided by Zod.

Advanced Zod Validation Examples

Zod offers a wide range of validation methods beyond basic string and length checks. Here are a few examples to illustrate its power in form validation:

These advanced features allow for highly specific and complex form validation rules, all while maintaining type safety.

Best Practices for Form Validation

When implementing form validation with React Hook Form and Zod, consider these best practices:

MethodDescriptionExample
z.number()Validates a numberz.number().min(18, ‘Must be at least 18’)
z.date()Validates a Date objectz.date().max(new Date(), ‘Date cannot be in the future’)
z.union()Validates against multiple typesz.union([z.string(), z.number()])
z.array()Validates an arrayz.array(z.string().min(1, ‘Item cannot be empty’)).min(1, ‘At least one item is required’)
z.enum()Validates against a predefined set of valuesz.enum([‘admin’, ‘user’], { message: ‘Invalid role’ })
z.refine() / z.superRefine()Custom validation logic for advanced scenariosz.string().refine(val => val.includes(‘@’), { message: ‘Must contain an @ symbol’ })

These advanced features allow for highly specific and complex form validation rules, all while maintaining type safety.

Best Practices for Form Validation

When implementing form validation with React Hook Form and Zod, consider these best practices:

  • Granular Validation: Break down complex forms into smaller, manageable Zod schemas. This improves readability and maintainability.
  • User Experience: Provide immediate and clear feedback to users about validation errors. This helps them correct their input quickly and efficiently.
  • Server-Side Validation: Always complement client-side form validation with server-side validation. Client-side validation is for user experience; server-side validation is for security and data integrity.
  • Reusable Components: Create reusable input components that encapsulate the register and error display logic. This promotes consistency and reduces code duplication.

Conclusion

By combining React Hook Form with Zod and Zod Resolver, we get a very simple yet powerfull way to handle form submission and validation without writing too much code. This makes our code highly readble and maintainable in future. Reducing development time and increase code quality. In future if we have to update the form validation logic, we can just update the zod schema and everything else is handled automatically.

Important Links:

Technology এর সকল আপডেট সবার আগে বিস্তারিত পেতে চেক করুন

Scroll to Top