ReactMedium
Form validation?
Validate forms in layers: native HTML constraints for instant, free checks; a schema (Zod or Valibot) shared between client and server for real rules; inline, accessible error messages shown at the right time (on blur or submit, not on every keystroke); and always validate again on the server, because client validation can be bypassed.
Layers
- HTML attributes:
required,type="email",minLength,pattern,min/max. The browser blocks submission and provides:invalidstyling. UsenoValidateon the form if you render custom messages. - Schema validation: describe rules once,
z.object({ email: z.string().email() }), infer TypeScript types, and reuse on the server. - Form library integration: React Hook Form with
zodResolver, TanStack Form validators. - Server validation: in the API or Server Function; return field errors in a consistent shape and display them (React 19
useActionState).
When to show errors
- After the field is blurred ("touched") or on submit, then live while the user fixes it.
- Not on first keystroke, which feels aggressive.
Accessibility
- Associate messages with inputs:
aria-describedbyandaria-invalid="true". - Use
role="alert"or a live region for submit-time errors. - Move focus to the first invalid field on submit.
- Do not rely on color alone.
UX details
Keep user input on error, disable the submit button only while submitting (not because the form is invalid, which hides the reason), and show a summary for long forms.
Code example
tsx
1import { useForm } from "react-hook-form";2import { zodResolver } from "@hookform/resolvers/zod";3import { z } from "zod";45// One schema: used here and on the server6export const SignupSchema = z7 .object({8 email: z.string().email("Enter a valid email"),9 password: z.string().min(12, "At least 12 characters"),10 confirm: z.string(),11 })12 .refine((d) => d.password === d.confirm, { path: ["confirm"], message: "Passwords do not match" });1314type Signup = z.infer<typeof SignupSchema>;1516export function SignupForm() {17 const { register, handleSubmit, formState: { errors, isSubmitting } } = useForm<Signup>({18 resolver: zodResolver(SignupSchema),19 mode: "onTouched", // validate after blur, then on change20 });2122 const onSubmit = async (data: Signup) => {23 await fetch("/api/signup", { method: "POST", body: JSON.stringify(data) }); // server validates again24 };2526 return (27 <form onSubmit={handleSubmit(onSubmit)} noValidate>28 <input type="email" {...register("email")} aria-invalid={!!errors.email} aria-describedby="email-err" />29 <p id="email-err" role="alert">{errors.email?.message}</p>30 <input type="password" {...register("password")} aria-invalid={!!errors.password} />31 <p role="alert">{errors.password?.message}</p>32 <input type="password" {...register("confirm")} aria-invalid={!!errors.confirm} />33 <p role="alert">{errors.confirm?.message}</p>34 <button disabled={isSubmitting}>{isSubmitting ? "Creating…" : "Create account"}</button>35 </form>36 );37}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.