ReactMedium

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

  1. Values state (or uncontrolled inputs read via FormData).
  2. A pure validator: validate(values) => errors, returning { email?: string; password?: string }.
  3. Touched state: show a field's error only after it was blurred or the form was submitted.
  4. Submit handler: run validation, focus the first invalid field, otherwise submit.
  5. 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-invalid and aria-describedby linking 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 noValidate on 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

tsx
1import { useRef, useState } from "react";
2
3type Values = { email: string; password: string; confirm: string };
4type Errors = Partial<Record<keyof Values, string>>;
5
6export 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}
15
16export 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 render
21 const show = (f: keyof Values) => touched[f] && errors[f];
22
23 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 );
31
32 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 }
39
40 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.

Open in study app