Form validation

Topic 3 of 3 in Forms7 min readIntermediateFree course

Overview

Validation stops users from submitting bad data — and good validation tells them, clearly and kindly, how to fix it. This lesson goes from built-in browser validation, to your own logic, to the tools most React teams use for real forms: React Hook Form and Zod.

Security first: client-side validation is a convenience for users. Anyone can bypass it with DevTools or by calling your API directly, so your server must always validate too.

Level 1: HTML validation

Browsers validate forms for free:

JSX
<form action={signup}>
  <input name="email" type="email" required />
  <input name="password" type="password" required minLength={8} />
  <input name="age" type="number" min={13} max={120} />
  <input name="username" pattern="[a-z0-9_]{3,20}" title="3–20 lowercase letters, numbers or _" />
  <button type="submit">Sign up</button>
</form>

The browser blocks submission and shows a message next to the first invalid field. It’s accessible and needs no JavaScript — but the messages’ look and wording are controlled by the browser, and you can’t easily show all errors at once or validate across fields (like “passwords match”).

Level 2: your own validation

For custom messages, validate in your action or submit handler and keep errors in state:

JSX
function validate(values) {
  const errors = {};
  if (!values.name.trim()) errors.name = 'Please enter your name';
  if (!values.email.includes('@')) errors.email = 'Enter a valid email address';
  if (values.password.length < 8) errors.password = 'Use at least 8 characters';
  return errors;
}

function SignupForm({ onSignup }) {
  const [errors, setErrors] = useState({});

  function handleSubmit(e) {
    e.preventDefault();
    const values = Object.fromEntries(new FormData(e.currentTarget));
    const nextErrors = validate(values);
    setErrors(nextErrors);
    if (Object.keys(nextErrors).length === 0) onSignup(values);
  }

  return (
    <form onSubmit={handleSubmit} noValidate>
      <label htmlFor="email">Email</label>
      <input
        id="email"
        name="email"
        aria-invalid={errors.email ? 'true' : 'false'}
        aria-describedby={errors.email ? 'email-error' : undefined}
      />
      {errors.email && <p id="email-error" className="error">{errors.email}</p>}
      {/* …other fields… */}
      <button type="submit">Sign up</button>
    </form>
  );
}

noValidate turns off the browser’s built-in bubbles so your messages are the only ones shown.

When to show errors

Validating on every keystroke from the first character is hostile — “Invalid email” appears before the user has finished typing. Good defaults:

  • validate a field when the user leaves it (onBlur) or on submit,
  • once a field has shown an error, re-validate it as they type, so the message disappears as soon as it’s fixed,
  • on submit, move focus to the first invalid field.

Accessible errors

  • Put the message in the DOM near the field, and link it with aria-describedby so screen readers read it with the field.
  • Set aria-invalid="true" on invalid inputs.
  • Don’t rely on colour alone — red borders need text too.
  • Every input needs a <label>; placeholders aren’t labels.

Level 3: schemas with Zod

Writing if statements for every rule gets repetitive, and the same rules usually exist on the server. A schema describes the shape and rules of your data once:

JavaScript
import { z } from 'zod';

export const signupSchema = z.object({
  name: z.string().trim().min(2, 'Name must be at least 2 characters'),
  email: z.email('Enter a valid email'),
  password: z.string().min(8, 'Use at least 8 characters'),
  age: z.coerce.number().int().min(13, 'You must be 13 or older'),
});

const result = signupSchema.safeParse(Object.fromEntries(formData));
if (!result.success) {
  console.log(result.error.issues);   // [{ path: ['email'], message: 'Enter a valid email' }, …]
} else {
  console.log(result.data);           // typed, trimmed, coerced values
}

Share the schema file between your React app and your Node API and you have one definition of “valid”, enforced in both places. (Zod 4’s z.email() replaces the older z.string().email().)

Level 4: React Hook Form

For forms with many fields, React Hook Form handles values, errors, touched fields, submission state and focus management. It uses uncontrolled inputs under the hood, so typing doesn’t re-render the whole form.

Terminal
npm install react-hook-form zod @hookform/resolvers
JSX
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { signupSchema } from './schemas.js';

export function SignupForm({ onSignup }) {
  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = useForm({
    resolver: zodResolver(signupSchema),
    defaultValues: { name: '', email: '', password: '' },
  });

  return (
    <form onSubmit={handleSubmit(onSignup)} noValidate>
      <label htmlFor="name">Name</label>
      <input id="name" aria-invalid={!!errors.name} {...register('name')} />
      {errors.name && <p role="alert">{errors.name.message}</p>}

      <label htmlFor="email">Email</label>
      <input id="email" type="email" aria-invalid={!!errors.email} {...register('email')} />
      {errors.email && <p role="alert">{errors.email.message}</p>}

      <button type="submit" disabled={isSubmitting}>Sign up</button>
    </form>
  );
}
  • register('name') returns the props (name, ref, onChange, onBlur) that connect an input to the form — spread them onto the input.
  • handleSubmit(fn) validates everything and calls fn(values) only when the data is valid. If fn is async, isSubmitting is true until it finishes.
  • errors holds a message per invalid field.
  • zodResolver(schema) plugs a Zod schema in as the validation rules.

Useful extras: mode: 'onTouched' to validate on blur, reset() to clear the form, setError('email', { message: 'Already registered' }) for server-side errors, and useFieldArray for dynamic lists of fields.

Cross-field rules

Use refine on the schema for rules involving more than one field, and set path so the error appears on the right input:

JavaScript
const schema = z
  .object({ password: z.string().min(8), confirm: z.string() })
  .refine((v) => v.password === v.confirm, {
    message: 'Passwords don’t match',
    path: ['confirm'],
  });

Showing server errors

Even with perfect client validation, the server may reject a submission (“email already registered”). Map those responses back onto fields:

JSX
async function onSubmit(values) {
  const res = await fetch('/api/signup', { method: 'POST', body: JSON.stringify(values), headers: { 'Content-Type': 'application/json' } });
  if (res.status === 409) {
    setError('email', { message: 'An account with this email already exists' });
    return;
  }
  onSignup(await res.json());
}

Which approach?

Form Approach
Search box, newsletter signup HTML validation + form action
A few fields with custom messages useActionState with your own checks, or a Zod schema
Large forms, dynamic fields, complex rules React Hook Form + Zod

Write helpful messages: say what’s wrong and how to fix it — “Use at least 8 characters, including a number” beats “Invalid password”.

Exercise

A validated registration form

Use React Hook Form with a Zod schema to build RegisterForm({ onRegister }) with name (2–50 characters), email (valid email), password (at least 8 characters, containing a number) and confirm password (must match). Show each field’s error message under it, connect it with aria-describedby, mark invalid fields with aria-invalid, and call onRegister({ name, email, password }) only when everything is valid. Disable the button while submitting.

JavaScript
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

const schema = z.object({
  // your code here
});

export function RegisterForm({ onRegister }) {
  // your code here
}

Summary

  • Start with HTML validation attributes (required, type="email", minLength, pattern) — they’re free and accessible.
  • Show errors after the user leaves a field or submits, not on the first keystroke.
  • Connect error messages to inputs with aria-describedby and mark them with aria-invalid.
  • A schema library like Zod describes the rules once and can be shared with your API.
  • React Hook Form manages values, errors and submission with uncontrolled inputs, so large forms stay fast.
  • Client-side validation is for user experience; the server must always validate again.