Form validation logic
Form validation logic checks each field against rules, collects error messages per field, decides when to show them (on blur, then live while correcting, and on submit), blocks submission while invalid, and focuses the first invalid field. A clean implementation separates a pure validate(values) function from the form component so the rules are easy to test and reuse.
Building blocks
- Values state (or uncontrolled inputs read via
FormData). - A pure validator:
validate(values) => errors, returning{ email?: string; password?: string }. - Touched state: show a field's error only after it was blurred or the form was submitted.
- Submit handler: run validation, focus the first invalid field, otherwise submit.
- Server errors: merge field errors returned by the API.
Rules commonly checked
Required fields, email format, length limits, password strength, matching confirmation, numeric ranges, dates in the future, and async checks such as username availability (debounced).
UX and accessibility
aria-invalidandaria-describedbylinking inputs to their messages.- Messages that say how to fix the problem ("At least 12 characters").
- Do not disable the submit button just because the form is invalid; let users submit and see errors.
- Preserve input on errors.
- Use
noValidateon the form if you replace native browser messages.
In production
Use a schema library (Zod) with React Hook Form or TanStack Form, and validate again on the server.
Code example
1import { useRef, useState } from "react";23type Values = { email: string; password: string; confirm: string };4type Errors = Partial<Record<keyof Values, string>>;56export function validate(v: Values): Errors {7 const e: Errors = {};8 if (!v.email.trim()) e.email = "Email is required";9 else if (!/^\S+@\S+\.\S+$/.test(v.email)) e.email = "Enter a valid email";10 if (v.password.length < 12) e.password = "Use at least 12 characters";11 else if (!/\d/.test(v.password)) e.password = "Include at least one number";12 if (v.confirm !== v.password) e.confirm = "Passwords do not match";13 return e;14}1516export function SignupForm() {17 const [values, setValues] = useState<Values>({ email: "", password: "", confirm: "" });18 const [touched, setTouched] = useState<Partial<Record<keyof Values, boolean>>>({});19 const formRef = useRef<HTMLFormElement>(null);20 const errors = validate(values); // derived on every render21 const show = (f: keyof Values) => touched[f] && errors[f];2223 const field = (name: keyof Values, type = "text") => (24 <div>25 <label htmlFor={name}>{name}</label>26 <input id={name} name={name} type={type} value={values[name]} aria-invalid={!!show(name)} aria-describedby={`${name}-err`}27 onChange={(e) => setValues({ ...values, [name]: e.target.value })} onBlur={() => setTouched({ ...touched, [name]: true })} />28 <p id={`${name}-err`} role="alert">{show(name) || ""}</p>29 </div>30 );3132 function onSubmit(e: React.FormEvent) {33 e.preventDefault();34 setTouched({ email: true, password: true, confirm: true });35 const first = Object.keys(errors)[0];36 if (first) return formRef.current?.querySelector<HTMLInputElement>(`[name="${first}"]`)?.focus();37 console.log("submit", values);38 }3940 return <form ref={formRef} onSubmit={onSubmit} noValidate>{field("email", "email")}{field("password", "password")}{field("confirm", "password")}<button>Sign up</button></form>;41}
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.