Sub topic 12
Building validated forms
This chapter assumes you know React hooks, basic TypeScript, and the cn and variant patterns from earlier chapters. You will connect a Zod schema to React Hook Form, so the schema is the single source of validation rules and the form's TypeScript types.
The working model
Three libraries each do one job:
- Zod describes valid data and produces error messages.
- React Hook Form tracks field values, submission, and errors. It registers inputs as uncontrolled, so typing does not re-render the whole form.
@hookform/resolversconnects the two.zodResolverruns your schema whenever the form validates and converts Zod issues into React Hook Form errors.
npm install react-hook-form zod @hookform/resolversA minimal validated form
This form uses plain elements so the validation logic is easy to see.
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"
const schema = z.object({
email: z.string().email("Enter a valid email address"),
})
type FormValues = z.infer<typeof schema>
export function EmailForm() {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<FormValues>({ resolver: zodResolver(schema) })
return (
<form onSubmit={handleSubmit((values) => console.log(values))}>
<label htmlFor="email">Email</label>
<input id="email" type="email" {...register("email")} aria-invalid={!!errors.email} />
{errors.email && <p role="alert">{errors.email.message}</p>}
<button type="submit">Subscribe</button>
</form>
)
}Three details matter here:
z.infer<typeof schema>givesFormValuesits type, so you never write the type by hand and the two cannot drift apart.register("email")returnsname,onChange,onBlur, andref. Spreading it wires the input to the form.aria-invalidandrole="alert"let screen readers announce the failure. A label tied to the input withhtmlForgives the field an accessible name.
Using shadcn/ui components
Replace the plain elements with owned components such as Input and Button. The shadcn/ui Input forwards its ref and spreads props onto a native <input>, so {...register("email")} works unchanged. The same holds for Button with type="submit".
Components that do not expose a native input, such as a Radix Select or Checkbox, cannot take register directly. They report changes through callbacks like onValueChange or onCheckedChange. For these, use Controller (or the control prop) to bridge the value and the change handler.
The CLI also offers a form component that wraps Controller with field, label, and message helpers. It is optional. The pattern above is enough when your fields are native inputs.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Errors never appear | Missing `resolver`, or the field name differs from the schema key | Pass `zodResolver(schema)` and match names exactly |
| Number field fails with "expected number" | HTML inputs return strings | Use `z.coerce.number()` or `register("age", { valueAsNumber: true })` |
| Select or checkbox value stays empty | Component is not a native input | Wrap it in `Controller` |
| Optional text field fails | Empty input is `""`, not `undefined` | Allow `.or(z.literal(""))` or transform it |
Exercise
A form field uses a shadcn/ui Select, built on a Radix primitive. Calling register("country") on it does not update the form value. Why, and what do you use instead?
Show answer
The Radix Select does not render a native input that register can attach a ref and change event to. It reports changes through onValueChange. Wrap it in React Hook Form's Controller and pass its field.value and field.onChange to the component's value and onValueChange props.