Imdadullah Babu
Full Stack Developer
2024-02-05
Full Stack Developer
1npm install react-hook-form zod @hookform/resolvers
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});
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}
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.
© 2024 IMDOS | All right reserved