2024-02-05

Validate Form with React Hook Form and Zod in NextJS 14

In modern web development, form validation is a crucial aspect of creating user-friendly and secure applications. In this guide, we'll explore how to leverage the power of react-hook-form along with zod for robust form validation in a React application.

Imdad

Imdadullah Babu

Full Stack Developer

[object Object]

Benefits of Using `react-hook-form` and `zod`

  1. Easy Integration and API Simplicity: react-hook-form simplifies form management by providing a straightforward API, making it easy to integrate into React applications. The integration of zod adds a layer of schema-based validation, ensuring data integrity and correctness.
  2. Declarative Validation with zod: zod is a TypeScript-first schema declaration and validation library. By using zod with react-hook-form, you can define your form's validation rules declaratively, making your codebase more readable and maintainable.
  3. Dynamic Schema Expansion: One of the significant advantages of this approach is the ability to create modular and expandable validation schemas. The provided example showcases a simple login form, but additional validation schemas can easily be added for other forms in your application.

Step-by-Step Implementation

Step 1: Install Necessary Packages

1npm install react-hook-form zod @hookform/resolvers

Step 2: Create a Validation Schema

Create a file `validation-schema.js`:

1import { z } from "zod";
2
3export const loginSchema = z.object({
4  email: z.string().email("Invalid email address"),
5  password: z.string().min(6, "Password must be at least 6 characters"),
6});

Step 3: Import and Configure in Your Component

In your component file:

1import { useForm } from "react-hook-form";
2import { zodResolver } from "@hookform/resolvers/zod";
3import { loginSchema } from "@/lib/validation-schema";
4import Input from "@/components/Input";
5import Button from "@/components/Button";
6
7export default function Login() {
8  const {
9    register,
10    handleSubmit,
11    formState: { errors },
12  } = useForm({
13    resolver: zodResolver(loginSchema),
14  });
15
16  const onSubmit = async (data) => {
17    console.log(data);
18  };
19
20  return (
21    <>
22      <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col space-y-2">
23        <Input
24          type="email"
25          label="Email"
26          {...register("email")}
27          isInvalid={Boolean(errors?.email)}
28          errorMessage={errors?.email?.message}
29        />
30        <Input
31          type="password"
32          label="Password"
33          {...register("password")}
34          isInvalid={Boolean(errors?.password)}
35          errorMessage={errors?.password?.message}
36        />
37        <Button type="submit">Login</Button>
38      </form>
39    </>
40  );
41}

Conclusion

By following these steps, you can seamlessly integrate react-hook-form and zod into your React application, ensuring a clean and efficient form validation process. This approach not only enhances the user experience but also contributes to the maintainability and scalability of your codebase. Experiment with different validation schemas to meet the specific requirements of your forms and build a robust foundation for your application's data integrity.

Share with your friends

IMDOS.IN

© 2024 IMDOS | All right reserved