← Back to React, page 4

react-0063 · Easy fresher

How do you implement form validation in plain React without a library?

Keep the field values in state, write a pure validate function that returns an errors object, and run it on submit (and optionally on blur for touched fields). Show errors next to fields, link them with aria-describedby, and block the submit when errors exist. Keep validation logic separate so it can be tested, and always validate again on the server.

Full answer

A form needs three things: values, errors and a moment when errors appear. Start with controlled inputs for the values. Then write validate(values), a plain function that returns an object such as { email: 'Enter a valid email' }. An empty object means valid. Because the function has no React in it, you can test it directly.

When to show errors is a user experience choice. Showing everything while the user is still typing is annoying. A common rule is to show an error after a field has been blurred (touched) or after a submit attempt. Keep a touched or submitted flag for that.

On submit: call event.preventDefault(), run validate, store the errors, and stop if there are any. If valid, send the data. Move focus to the first invalid field or to an error summary, so keyboard and screen reader users notice. Render each message in an element with an id, set aria-invalid on the input and link it with aria-describedby.

Derived values need no state. The errors can be calculated during render from the values: const errors = validate(values). Only store whether to show them.

Client checks are for convenience. A user can bypass them, so the server must validate again and return field errors that you show in the same place.

When forms grow, with many fields, arrays or async rules, move to React Hook Form or a similar library, plus a schema library such as Zod.

The example validates name and email and shows a success message.

jsx
import { useState } from 'react';

function validate(values) {
  const errors = {};
  if (values.name.trim() === '') errors.name = 'Name is required';
  if (!/^\S+@\S+\.\S+$/.test(values.email)) errors.email = 'Enter a valid email';
  return errors;
}

export default function RegisterForm() {
  const [values, setValues] = useState({ name: '', email: '' });
  const [submitted, setSubmitted] = useState(false);
  const [done, setDone] = useState(false);

  const errors = validate(values);

  function handleChange(event) {
    setValues({ ...values, [event.target.name]: event.target.value });
  }

  function handleSubmit(event) {
    event.preventDefault();
    setSubmitted(true);
    if (Object.keys(errors).length === 0) setDone(true);
  }

  return (
    <form onSubmit={handleSubmit} noValidate>
      <label>
        Name
        <input name="name" value={values.name} onChange={handleChange} aria-invalid={submitted && !!errors.name} aria-describedby="name-error" />
      </label>
      {submitted && errors.name && <p id="name-error" role="alert">{errors.name}</p>}
      <label>
        Email
        <input name="email" value={values.email} onChange={handleChange} aria-invalid={submitted && !!errors.email} aria-describedby="email-error" />
      </label>
      {submitted && errors.email && <p id="email-error" role="alert">{errors.email}</p>}
      <button type="submit">Register</button>
      {done && <output>Welcome, {values.name}</output>}
    </form>
  );
}

The check submitted an empty form, then typed valid values and submitted again. Output of the run: empty submit: Name is required | Enter a valid email valid submit: Welcome, Asha

Key points

  • Controlled values plus a pure validate function returning an errors object.
  • Show errors after blur or submit, not on the first keystroke.
  • Use aria-invalid and aria-describedby, and move focus to the first error.
  • Derive errors from values. Store only whether they are visible.
  • Server validation is mandatory. Libraries help when forms get large.

Common mistakes

  • Validating only on the client.
  • Showing errors on every keystroke before the user finished typing.
  • Hiding errors from screen readers by not linking them to inputs.
  • Putting the validation rules inside the JSX handlers where they cannot be tested.
  • Keeping a copy of the errors in state that can drift from the values.

Follow-ups

  • How would you add an async check such as "email already used"?
  • How does React Hook Form change the amount of rendering a form does?
  • How would you share validation rules between client and server?

Tips

  • Describe the three pieces (values, errors, when to show) before coding.
  • Mention accessibility of errors. Many answers skip it.
  • Say you would move to React Hook Form for large forms.