Skip to content

Instantly share code, notes, and snippets.

@KolbySisk
Created January 17, 2022 16:33
Show Gist options
  • Save KolbySisk/3439e4e56f430b22221790636631b579 to your computer and use it in GitHub Desktop.
Save KolbySisk/3439e4e56f430b22221790636631b579 to your computer and use it in GitHub Desktop.
React Hook Form with Zod Example
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