-
-
Save sandrig/98c9a7cad96ca71ea5cfb08a609f12da to your computer and use it in GitHub Desktop.
React Hook Form with Zod Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { useForm } from "react-hook-form"; | |
| import { zodResolver } from "@hookform/resolvers/zod"; | |
| import * as z from "zod"; | |
| const schema = z.object({ | |
| email: z.string().email().min(2), | |
| password: z.string().min(6) | |
| }); | |
| export default function RhfFormWithZod() { | |
| const { | |
| register, | |
| handleSubmit, | |
| reset, | |
| formState: { errors } | |
| } = useForm({ | |
| resolver: zodResolver(schema) | |
| }); | |
| const processForm = async (data) => { | |
| await fetch("/api/form", { | |
| method: "POST", | |
| body: JSON.stringify(data) | |
| }); | |
| reset(); | |
| }; | |
| return ( | |
| <form | |
| onSubmit={handleSubmit(processForm)} | |
| style={{ display: "flex", flexDirection: "column", width: 300 }} | |
| > | |
| <input | |
| {...register("email", { required: true })} | |
| name="email" | |
| type="email" | |
| /> | |
| {errors.email?.message && <span>{errors.email?.message}</span>} | |
| <input | |
| {...register("password", { required: true, minLength: 6 })} | |
| name="password" | |
| type="password" | |
| /> | |
| {errors.password?.message && <span>{errors.password?.message}</span>} | |
| <button>Submit</button> | |
| </form> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment