How-To Guide

How to Validate Forms in React with Custom Hooks

Build a typed React form hook with validation timing, accessible errors, focus management, server errors, async checks, and tests for real user flows.

On this page

  1. Introduction
  2. Define typed values and rules
  3. Build the hook
  4. Wire accessible inputs
  5. Map server errors back to fields
  6. Add async checks carefully
  7. Test user-visible behavior
  8. Common pitfalls
  9. Conclusion

Introduction

React does not prescribe a form library. Controlled inputs are enough for a small form, but validation timing, touched state, error accessibility, async checks, and submission handling quickly turn into repeated code. A custom hook can centralize those rules without adopting a full form framework.

This tutorial builds a typed useForm hook with pure validation rules, validation on blur and submit, accessible error wiring, focus management, server-side error mapping, and a separate pattern for async checks. It also covers the mistakes that make hand-written form hooks fragile: stale state, stateful regular expressions, rule objects that change identity every render, and error messages that are invisible to assistive technology.

Define typed values and rules

Start with the data shape. Keep rules outside the component so their identity is stable and they can be unit-tested without React:

type Values = Record<string, string>;
type FieldName<T extends Values> = keyof T & string;
type Rule<T extends Values> = (value: string, values: T) => string | undefined;
type Rules<T extends Values> = Partial<Record<FieldName<T>, Rule<T>[]>>;

type LoginValues = { email: string; password: string };

const loginRules: Rules<LoginValues> = {
  email: [
    (value) => (value.trim() ? undefined : 'Email is required'),
    (value) =>
      /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value)
        ? undefined
        : 'Enter a valid email address',
  ],
  password: [
    (value) => (value.length >= 8 ? undefined : 'Use at least 8 characters'),
  ],
};

Each rule returns an error message or undefined. Returning data instead of throwing makes rules composable and easy to test. Avoid the g flag on validation regular expressions: RegExp.prototype.test advances lastIndex on a global regex, so the same value can pass once and fail on the next call. If a rule needs a global regex, create it inside the function or reset lastIndex.

Do not trim a password silently. Trimming an email is usually helpful; trimming a password changes the credential. Normalize each field according to its meaning, not with a generic trim() on every value.

Build the hook

The hook owns values, touched fields, errors, submission state, and a server error:

import {
  useCallback,
  useEffect,
  useState,
  type ChangeEvent,
  type FormEvent,
} from 'react';

export function useForm<T extends Values>(initialValues: T, rules: Rules<T>) {
  const [values, setValues] = useState<T>(initialValues);
  const [errors, setErrors] = useState<Partial<Record<FieldName<T>, string>>>({});
  const [touched, setTouched] = useState<Partial<Record<FieldName<T>, boolean>>>({});
  const [submitting, setSubmitting] = useState(false);
  const [serverError, setServerError] = useState<string | null>(null);

  const validateField = useCallback(
    (name: FieldName<T>, value: string, all: T) => {
      for (const rule of rules[name] ?? []) {
        const message = rule(value, all);
        if (message) return message;
      }
      return undefined;
    },
    [rules]
  );

  const validateAll = useCallback(
    (all: T) => {
      const next: Partial<Record<FieldName<T>, string>> = {};
      for (const name of Object.keys(all) as FieldName<T>[]) {
        const message = validateField(name, all[name], all);
        if (message) next[name] = message;
      }
      return next;
    },
    [validateField]
  );

  const handleChange =
    (name: FieldName<T>) => (event: ChangeEvent<HTMLInputElement>) => {
      const value = event.target.value;
      const next = { ...values, [name]: value } as T;
      setValues(next);

      if (touched[name]) {
        setErrors((current) => ({
          ...current,
          [name]: validateField(name, value, next),
        }));
      }
      setServerError(null);
    };

  const handleBlur = (name: FieldName<T>) => () => {
    setTouched((current) => ({ ...current, [name]: true }));
    setErrors((current) => ({
      ...current,
      [name]: validateField(name, values[name], values),
    }));
  };

  const handleSubmit =
    (onValid: (values: T) => Promise<void>) =>
    async (event: FormEvent<HTMLFormElement>) => {
      event.preventDefault();
      if (submitting) return;

      const nextErrors = validateAll(values);
      setTouched(
        Object.fromEntries(
          Object.keys(values).map((key) => [key, true])
        ) as Partial<Record<FieldName<T>, boolean>>
      );
      setErrors(nextErrors);

      const firstInvalid = Object.keys(nextErrors)[0];
      if (firstInvalid) {
        const field = event.currentTarget.elements.namedItem(firstInvalid);
        if (field instanceof HTMLElement) field.focus();
        return;
      }

      setSubmitting(true);
      setServerError(null);
      try {
        await onValid(values);
      } catch (error) {
        setServerError(error instanceof Error ? error.message : 'Submit failed');
      } finally {
        setSubmitting(false);
      }
    };

  const setFieldErrors = useCallback(
    (fieldErrors: Partial<Record<FieldName<T>, string>>) => {
      setErrors(fieldErrors);
      setTouched(
        Object.fromEntries(
          Object.keys(fieldErrors).map((key) => [key, true])
        ) as Partial<Record<FieldName<T>, boolean>>
      );
    },
    []
  );

  return {
    values,
    errors,
    touched,
    submitting,
    serverError,
    setFieldErrors,
    handleChange,
    handleBlur,
    handleSubmit,
  };
}

The focus call uses form.elements.namedItem, so keep name attributes on inputs. Avoid indexing form.elements[0]; the DOM order can change when a field is added or reordered.

handleChange reads values from the render closure. For a form updated by several events in one tick, switch to a reducer or a ref that always holds the latest values. For ordinary typing, one event per render is the common case, and the simpler code is easier to review.

Wire accessible inputs

A label must be associated with its input. Errors need aria-describedby, and invalid fields need aria-invalid. An error summary at the top helps users of screen readers discover the count without tabbing through every field:

function LoginForm({ onSubmit }: { onSubmit: (values: LoginValues) => Promise<void> }) {
  const form = useForm<LoginValues>(
    { email: '', password: '' },
    loginRules
  );

  return (
    <form onSubmit={form.handleSubmit(onSubmit)} noValidate>
      {Object.keys(form.errors).length > 0 && (
        <p role="alert">
          {Object.keys(form.errors).length} field(s) need attention.
        </p>
      )}

      <label htmlFor="email">Email</label>
      <input
        id="email"
        name="email"
        type="email"
        autoComplete="email"
        value={form.values.email}
        onChange={form.handleChange('email')}
        onBlur={form.handleBlur('email')}
        aria-invalid={form.errors.email ? true : undefined}
        aria-describedby={form.errors.email ? 'email-error' : undefined}
      />
      {form.errors.email && <p id="email-error">{form.errors.email}</p>}

      <label htmlFor="password">Password</label>
      <input
        id="password"
        name="password"
        type="password"
        autoComplete="current-password"
        value={form.values.password}
        onChange={form.handleChange('password')}
        onBlur={form.handleBlur('password')}
        aria-invalid={form.errors.password ? true : undefined}
        aria-describedby={form.errors.password ? 'password-error' : undefined}
      />
      {form.errors.password && <p id="password-error">{form.errors.password}</p>}

      {form.serverError && <p role="alert">{form.serverError}</p>}

      <button type="submit" disabled={form.submitting}>
        {form.submitting ? 'Signing in…' : 'Sign in'}
      </button>
    </form>
  );
}

noValidate disables the browser’s native validation bubble so the custom messages are the single source of truth. If you keep native validation, do not also show a conflicting custom message.

Do not disable the submit button just because the form is invalid. The button is how users request validation. Disabling it hides the reason and removes a focus target. Disable it only while a valid submission is in flight to prevent duplicates.

Map server errors back to fields

The server is the final validator. Return a stable error shape such as { errors: { email: "..." } } and merge those errors into the same state:

async function submitLogin(
  values: LoginValues,
  setFieldErrors: (errors: Partial<Record<keyof LoginValues, string>>) => void
) {
  const response = await fetch('/api/login', {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(values),
  });

  if (response.status === 422) {
    const body = await response.json();
    setFieldErrors(body.errors);
    return;
  }
  if (!response.ok) throw new Error('Sign-in failed. Try again.');
}

The hook returns setFieldErrors, so pass it into the submit helper or call form.setFieldErrors(body.errors) from a submit handler that has access to the hook result. Keep server error text separate from client rule text: a duplicate-email error comes from the server and may change without a client release.

Add async checks carefully

Username availability and coupon-code checks are asynchronous. Do not put them in the synchronous rule array. Use a debounced effect with an abort signal:

function useAvailability(name: string) {
  const [status, setStatus] = useState<'idle' | 'checking' | 'available' | 'taken'>('idle');

  useEffect(() => {
    if (name.length < 3) {
      setStatus('idle');
      return;
    }

    const controller = new AbortController();
    const timer = window.setTimeout(async () => {
      setStatus('checking');
      try {
        const response = await fetch(
          `/api/username?name=${encodeURIComponent(name)}`,
          { signal: controller.signal }
        );
        setStatus(response.ok ? 'available' : 'taken');
      } catch {
        if (!controller.signal.aborted) setStatus('idle');
      }
    }, 300);

    return () => {
      window.clearTimeout(timer);
      controller.abort();
    };
  }, [name]);

  return status;
}

The cleanup cancels both the pending timer and the in-flight request, so an older response cannot overwrite a newer status. The server must still enforce uniqueness at write time; an availability check is advisory and can race with another user.

If an async check is required before submission, track its status separately and block only while it is checking. Do not block forever on a failed availability request; show a retry path.

Test user-visible behavior

Test the form through the DOM, not the hook internals. React Testing Library with userEvent exercises typing, blur, and submit:

import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, test, vi } from 'vitest';

test('shows field errors and focuses the first invalid field', async () => {
  const user = userEvent.setup();
  const onSubmit = vi.fn();
  render(<LoginForm onSubmit={onSubmit} />);

  await user.click(screen.getByRole('button', { name: /sign in/i }));

  expect(await screen.findByText('Email is required')).toBeInTheDocument();
  expect(screen.getByLabelText(/email/i)).toHaveFocus();
  expect(onSubmit).not.toHaveBeenCalled();
});

test('submits valid values', async () => {
  const user = userEvent.setup();
  const onSubmit = vi.fn().mockResolvedValue(undefined);
  render(<LoginForm onSubmit={onSubmit} />);

  await user.type(screen.getByLabelText(/email/i), '[email protected]');
  await user.type(screen.getByLabelText(/password/i), 'correct-horse');
  await user.click(screen.getByRole('button', { name: /sign in/i }));

  expect(onSubmit).toHaveBeenCalledWith({
    email: '[email protected]',
    password: 'correct-horse',
  });
});

Add a server-error test that mocks fetch to return 422 and asserts the field message appears. Add a test that a second click while onValid is pending does not call the server twice.

Common pitfalls

  • Validating everything on every keystroke. Errors appear before the user finishes typing; validate on blur and submit, then revalidate touched fields on change.
  • Disabling submit. Users cannot trigger validation or discover what is wrong.
  • Missing name attributes. Focus management and form serialization depend on them.
  • Stateful regular expressions. A global regex mutates lastIndex.
  • Unstable rules. Defining rules inline creates new arrays every render and can retrigger effects.
  • Unhandled async races. Abort or sequence requests so an old response cannot win.
  • Trusting client validation. The server must repeat every check.
  • Only using color for errors. Pair text and aria-invalid; color alone is not accessible.

Conclusion

A custom React form hook is a small state machine: values, touched fields, errors, and submission status. Keep rules pure and stable, validate on blur and submit, wire labels and error descriptions, focus the first invalid field, and merge server errors into the same model. The hook is not a replacement for a mature form library when requirements include nested arrays and complex schemas, but for a focused form it removes duplicated code without hiding browser or accessibility behavior.

Sources: React controlled components, WAI-ARIA form patterns, Testing Library user-event.

FAQ

Should the submit button be disabled until the form is valid?
Usually no. A disabled button gives no explanation and cannot be focused, so keyboard and screen-reader users may not know what is wrong. Allow submission, validate, show field errors, and move focus to the first invalid field.
When should validation run?
Validate on submit and revalidate a field on change after it has been touched. Validating every field on every keystroke creates noisy errors before the user has finished typing.
Can client-side validation replace server validation?
No. Client validation improves feedback, but a direct request can bypass it. The server must validate every field and return field-level errors that the form can display.

Related Examples

Interactive Tools for This Topic