Integrating React Hook Form and Zod

In this article we are going to learn how to make validation form using react hook form and zod

#React#NextJS#Tailwind#React-Hook-Form#Zod
Last updated: 3/6/2024

First let's install all required dependencies

bun add react-hook-form zod @hookform/resolvers

Then import to our page file

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

Create type for all required input form

type InputFormLogin = {
  email: string;
  password: string;
};

Then let's create our first schema validation using z function from zod.

const schema = z.object({
  email: z
    .string({ message: "Email is required" })
    .min(1, { message: "Email is required" })
    .email("Invalid email address"),
  password: z
    .string({ message: "Email is required" })
    .min(6, { message: "Password must be at least 6 characters" }),
});

Then set configuration for react-hook-form. We need import all required function like:

  1. register: This function enable react-hook-form which input are applied to.

  2. handleSubmit: We're gonna use this function to our form component (we added this function later)

  3. formstate:{error}: Then we're gonna display all error when input field is not match to our validation.

const {
  register,
  handleSubmit,
  formState: { errors },
} = useForm<InputFormLogin>({
  resolver: zodResolver(schema),
  mode: "onChange", // ganti sesuai keinginan
});

After that, add register function to your input then name of that input

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

This code for display all error when input are not match from our validation

{errors.username && <span>{errors.username.message}</span>}

Then create function to handle submitted form

const onSubmit: SubmitHandler<InputFormLogin> = (data) => {
  console.log(data);
};

and lastly add that function to your form

<form onSubmit={handleSubmit(onSubmit)}>
  {/* Form fields and error messages */}
</form>

Reference : Simplifying Form Validation with Zod and React Hook Form - DEV Community

Zod : Zod | Documentation

React Hook Form : Get Started

Created by: shousyadev