Sub topic 12
Building validated forms
This chapter connects the shadcn/ui form components to React Hook Form and Zod. It assumes you have read the chapters on customizing owned components and on Radix primitives. It also assumes you can write React function components with hooks and basic TypeScript. You do not need prior experience with either form library.
The division of labor
Three pieces cooperate in a validated form, and each has one job.
- Zod describes what valid data looks like. A schema is a runtime object that checks values and produces error messages.
- React Hook Form tracks field values, touched state, and errors. It avoids re-rendering the whole form on every keystroke.
@hookform/resolversis the adapter.zodResolver(schema)turns Zod's output into the error shape React Hook Form expects.
shadcn/ui adds a fourth layer. Its Form components are thin wrappers that connect a styled input to an error message and to the accessibility attributes screen readers need. They hold no validation logic.
The plain version first
The smallest working setup uses no shadcn/ui components at all. It shows the mechanics that the wrappers later hide.
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>
)
}Four details matter here.
z.infer<typeof schema>derives the TypeScript type from the schema. You never write the type by hand, so the two cannot drift apart.register("email")returnsname,onChange,onBlur, andref. Spreading them makes the field uncontrolled. The browser holds the value, and React Hook Form reads it through the ref.handleSubmitruns the resolver first. Your callback runs only when validation passes.aria-invalidandrole="alert"are what let assistive technology announce the problem. You must add them yourself in the plain version.
Writing schemas that match the form
Field-level rules go on each field. Rules that compare fields go on the object with refine.
import { z } from "zod"
export const signupSchema = z
.object({
email: z.string().email("Enter a valid email address"),
password: z.string().min(8, "Use at least 8 characters"),
confirm: z.string(),
})
.refine((values) => values.password === values.confirm, {
message: "Passwords do not match",
path: ["confirm"],
})
export type SignupValues = z.infer<typeof signupSchema>The path option decides which field receives the error. Without it, the error attaches to the form root and no field shows it.
A gotcha: object-level refine runs only when every field rule has already passed. A user with an invalid email and mismatched passwords sees only the email error first. The mismatch message appears after they fix the email. This is normal behavior, but it surprises people during testing.
Connecting shadcn/ui components
Add the pieces with the CLI:
npx shadcn@latest add form input buttonThe form component is copied into components/ui/form.tsx, like every other component, so you own it. It exports Form, FormField, FormItem, FormLabel, FormControl, FormDescription, and FormMessage.
Formis React Hook Form'sFormProvider. You pass it the object returned byuseForm.FormFieldwraps React Hook Form'sController. It gives its render function afieldobject withvalue,onChange,onBlur,name, andref.FormItemgenerates a unique id for one field and shares it through context.FormLabel,FormControl,FormDescription, andFormMessageread that context and wire up the attributes.
FormControl uses the Slot from the asChild chapter. It clones its single child and adds id, aria-invalid, and aria-describedby. The description and the message are linked to the input without you writing any ids.
"use client"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { Button } from "@/components/ui/button"
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { signupSchema, type SignupValues } from "@/lib/signup-schema"
export function SignupForm() {
const form = useForm<SignupValues>({
resolver: zodResolver(signupSchema),
defaultValues: { email: "", password: "", confirm: "" },
})
async function onSubmit(values: SignupValues) {
const res = await fetch("/api/signup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(values),
})
if (res.status === 409) {
form.setError("email", { message: "This email is already registered" })
}
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input type="email" autoComplete="email" {...field} />
</FormControl>
<FormDescription>We never share your address.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Password</FormLabel>
<FormControl>
<Input type="password" autoComplete="new-password" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="confirm"
render={({ field }) => (
<FormItem>
<FormLabel>Confirm password</FormLabel>
<FormControl>
<Input type="password" autoComplete="new-password" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" disabled={form.formState.isSubmitting}>
Create account
</Button>
</form>
</Form>
)
}FormMessage renders nothing when the field has no error. When there is one, it shows the Zod message text, and FormLabel takes on the destructive color from your theme.
Server errors and submission state
Client validation cannot know that an email is already taken. The submit handler above uses setError to put a server-side message on a specific field. FormMessage shows it exactly like a Zod message. The error clears the next time that field is revalidated.
formState.isSubmitting is true while an async onSubmit promise is pending. Disabling the button with it prevents double submission. Return or await the promise, because a handler that does not wait leaves isSubmitting false almost immediately.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Console warning about switching from uncontrolled to controlled | `defaultValues` is missing, so `field.value` starts as `undefined` | Give every field a default, using `""` for text |
| Mismatch error never appears | `refine` has no `path`, or other fields still fail | Set `path` and fix the earlier field errors |
| Error text is shown but not announced | A custom field does not use `FormControl` | Wrap the input in `FormControl`, or add `aria-describedby` yourself |
| Number input yields a string | HTML inputs always return strings | Use `z.coerce.number()` or convert in `onChange` |
| Typing is slow in a large form | Reading `form.watch()` at the top level re-renders everything | Watch single fields, or move the reading component lower |
| Type error on `useForm<SignupValues>` with `zodResolver` | Schema uses `coerce` or `transform`, so input and output types differ | Check your Zod and resolver versions, and see the resolver documentation for the input and output generics |
Version note: Zod 4 prefers z.email() over z.string().email(). The older form still works, but it is marked deprecated. Use whichever matches your installed Zod, and keep zod and @hookform/resolvers upgraded together.
Components that are not native inputs
Select, Checkbox, and Switch from Radix do not take onChange. Map the field explicitly:
<Checkbox checked={field.value} onCheckedChange={field.onChange} />This is the main reason shadcn/ui uses Controller through FormField rather than register. Radix components expose value-based callbacks, and Controller bridges them to the form state.
Exercise
A signup form shows an error under the email field when the email is invalid, but never shows "Passwords do not match" even when the two passwords differ. The schema uses .refine((v) => v.password === v.confirm, { message: "Passwords do not match" }). Give two possible causes and the fix for each.
Show answer
First, the refine call has no path, so the error attaches to the form root instead of the confirm field, and no FormMessage shows it. Add path: ["confirm"]. Second, object-level refine runs only after every field rule passes, so the invalid email blocks it. The mismatch message appears once the email is fixed. Both can be true at once, so apply the path fix and then test with a valid email.