Simplified Yet Powerful React Form Validation with Zod: A Practical Guide
The Zod library provides a powerful toolset for JavaScript and TypeScript developers to streamline data validation processes. In the previous article, we discussed the general features and advantages of Zod. Now, let’s shift our focus to the practical usage of this library by demonstrating how to integrate Zod into React form validation processes.
Right below, you can find a simple Zod example for validating a user form:
npm install @hookform/resolvers
Now, let’s delve into using Zod in your code. Begin by importing the library into your TypeScript file:
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
const schema = z
.object({
name: z
.string()
.trim()
.min(3, { message: "Write your error message" }),
email: z
.string({
required_error: "Write your error message",
})
.email()
.trim()
.min(5, { message: "Write your error message" }),
password: z
.string()
.trim()
.min(5, { message: "Write your error message" }),
;
export default function Example() {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: zodResolver(schema),
});
}
const onSubmit = async (data) => {
console.log(data)
};
<form onSubmit={handleSubmit((d)=> onSubmit(d))}>
<input {...register("name")}
id="name"
name="name"
type="text"
autoComplete="name" />
{errors.name && (
<p>{errors.name?.message?.toString()}</p>
)}
<input {...register("email")}
id="email"
name="email"
type="email"
autoComplete="email" />
{errors.email&& (
<p>{errors.email?.message?.toString()}</p>
)}
<input {...register("password")}
id="password"
name="password"
type="password"
/>
{errors.password&& (
<p>{errors.password?.message?.toString()}</p>
)}
<button type="submit"> Submit</button>
</form>
This example demonstrates the integration of Zod with TypeScript and a basic scenario for validating a user form. Feel free to expand this basic example to fit your specific project requirements.
More details you can find from here.