React Hook Form Zod Typed Resolver
Wire React Hook Form to a Zod resolver so field rules live in one schema, errors arrive per-field, and values stay typed through submit.
Code
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
const SignupSchema = z.object({
email: z.string().email('enter a valid email'),
password: z
.string()
.min(8, 'at least 8 characters')
.regex(/[A-Z]/, 'needs an uppercase letter')
.regex(/\d/, 'needs a digit'),
confirm: z.string(),
}).refine((data) => data.password === data.confirm, {
message: 'passwords do not match',
path: ['confirm'],
});
type SignupValues = z.infer<typeof SignupSchema>;
function SignupForm({ onDone }: { onDone: (values: SignupValues) => void }) {
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<SignupValues>({
resolver: zodResolver(SignupSchema),
defaultValues: { email: '', password: '', confirm: '' },
});
return (
<form onSubmit={handleSubmit(onDone)}>
<input {...register('email')} placeholder="email" />
{errors.email && <p role="alert">{errors.email.message}</p>}
<input {...register('password')} type="password" placeholder="password" />
{errors.password && <p role="alert">{errors.password.message}</p>}
<input {...register('confirm')} type="password" placeholder="confirm" />
{errors.confirm && <p role="alert">{errors.confirm.message}</p>}
<button type="submit" disabled={isSubmitting}>Sign up</button>
</form>
);
}How the snippet works
One way to read it: the function SignupForm, doing all the work.
useForm, zodResolver, z are the only symbols borrowed from react-hook-form — the coupling is explicit and narrow.
What to watch for
- Plan for an install step:
react-hook-form,@hookform/resolvers/zodandzodare a real dependency, resolved by the package manager.
Using it
The main signature reads function SignupForm({ onDone }: { onDone: (values: SignupValues)
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Do I need to install anything before running this?
- Yes: `react-hook-form`, `@hookform/resolvers/zod` and `zod` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.