Sub topic 2
Deriving TypeScript Types with Zod
This chapter assumes you know React function components, hooks, TypeScript types and generics, HTML form fields, and async/await.
A Zod schema validates data at runtime. z.infer derives a TypeScript type from that same schema, so the validation rules and form type stay aligned.
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
const signUpSchema = z
.object({
email: z.string().min(1, "Email is required").email("Enter a valid email"),
password: z.string().min(8, "Use at least 8 characters"),
confirmPassword: z.string(),
})
.refine((data) => data.password === data.confirmPassword, {
message: "Passwords do not match",
path: ["confirmPassword"],
});
type SignUpValues = z.infer<typeof signUpSchema>;
export function SignUpForm() {
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<SignUpValues>({
resolver: zodResolver(signUpSchema),
mode: "onBlur",
defaultValues: {
email: "",
password: "",
confirmPassword: "",
},
});
const onSubmit = async (values: SignUpValues) => {
await fetch("/api/sign-up", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(values),
});
};
return (
<form onSubmit={handleSubmit(onSubmit)} noValidate>
<label htmlFor="email">Email</label>
<input id="email" type="email" {...register("email")} />
{errors.email && <p role="alert">{errors.email.message}</p>}
<label htmlFor="password">Password</label>
<input id="password" type="password" {...register("password")} />
{errors.password && <p role="alert">{errors.password.message}</p>}
<label htmlFor="confirmPassword">Confirm password</label>
<input
id="confirmPassword"
type="password"
{...register("confirmPassword")}
/>
{errors.confirmPassword && (
<p role="alert">{errors.confirmPassword.message}</p>
)}
<button type="submit" disabled={isSubmitting}>
Create account
</button>
</form>
);
}zodResolver adapts Zod’s result to React Hook Form. If parsing fails, the resolver places messages in formState.errors. handleSubmit calls onSubmit only after the schema passes.
mode controls when validation runs:
| Mode | Validation timing | Typical use |
|---|---|---|
| `onSubmit` | When the user submits | Minimal interruption |
| `onBlur` | When a field loses focus | Balanced feedback |
| `onChange` | After each change | Immediate feedback |
refine checks a rule involving multiple fields. Its path assigns the resulting error to one field, allowing the message to appear beside confirmPassword.
Exercise
Which option makes a cross-field password error appear beside the confirmation field?
Show answer
Pass path: ["confirmPassword"] to refine.