ReactBeginner

React Form Validation and Error Messages

Learn how to validate React forms: write a validate function, show errors after blur and submit, add accessible messages, and show a success state.

React CourseLesson 15 of 66 (23% complete)
All React lessons (66)View curriculum

What you will learn

A form that accepts anything is a form that causes problems: empty names, emails without an @, passwords of one letter. Validation checks the data and tells the user what to fix.

In this lesson you will build a registration form that checks its fields, shows clear error messages at the right moment, uses accessible markup so screen readers can announce the errors, and shows a success message when everything is correct. You should know controlled inputs from the previous lesson.

Validation basics

Good validation follows a few simple rules:

  • Tell the user what is wrong and how to fix it. Password must be at least 8 characters. is better than Invalid input.
  • Do not shout too early. Do not show Name is required the moment the page opens, or while the user is still typing their first letter.
  • Check again on submit. Even if the user never touched a field, pressing the submit button must catch the mistakes.
  • Never trust the browser alone. Client-side validation is for helping users. A server must validate again, because anyone can bypass the browser. See the JavaScript form validation lesson.

Step 1: write a validate function

The cleanest approach is a plain function that takes the form values and returns an object of errors. It has no state and no JSX, so it is easy to read and to test:

function validate(values) {
  const errors = {};

  if (values.name.trim().length < 2) {
    errors.name = "Name must be at least 2 characters.";
  }
  if (!/^\S+@\S+\.\S+$/.test(values.email)) {
    errors.email = "Enter a valid email address.";
  }
  if (values.password.length < 8) {
    errors.password = "Password must be at least 8 characters.";
  }

  return errors;
}

How it works:

  • It starts with an empty errors object.
  • For each field, if the rule fails, it adds a message under that field’s name.
  • If everything is fine, it returns {}, an empty object.

Examples of what it returns:

validate({ name: "", email: "abc", password: "123" })
→ { name: "Name must be at least 2 characters.",
    email: "Enter a valid email address.",
    password: "Password must be at least 8 characters." }

validate({ name: "Aisha", email: "[email protected]", password: "secret123" })
→ {}

The email rule /^\S+@\S+\.\S+$/ is a simple regular expression: some non-space characters, an @, more characters, a dot and more characters. It catches obvious mistakes, but it is not a perfect email checker. It is a good first check for beginners. The only real proof that an email works is sending a message to it.

Step 2: calculate the errors on every render

You might be tempted to store the errors in state. Do not. Errors can be calculated from the values, so they should not be state (the “calculate, do not store” idea from the state lessons):

const errors = validate(values);
const isValid = Object.keys(errors).length === 0;

Every time the user types, the component re-renders, validate runs again, and errors is always up to date. Object.keys(errors).length === 0 is true when there are no errors.

Step 3: decide when to show errors

If you show all errors immediately, the empty form is already covered in red. A better user experience is to show an error for a field only after the user has left that field (we say the field was touched), or after they tried to submit.

So we keep a second piece of state: which fields were touched.

const [touched, setTouched] = useState({});

function handleBlur(event) {
  setTouched({ ...touched, [event.target.name]: true });
}

onBlur fires when a field loses focus. The handler marks that field as touched, for example { email: true }. You saw the computed key [event.target.name] in the previous lesson.

The complete form

Put everything together:

import { useState } from 'react';

function validate(values) {
  const errors = {};

  if (values.name.trim().length < 2) {
    errors.name = "Name must be at least 2 characters.";
  }
  if (!/^\S+@\S+\.\S+$/.test(values.email)) {
    errors.email = "Enter a valid email address.";
  }
  if (values.password.length < 8) {
    errors.password = "Password must be at least 8 characters.";
  }

  return errors;
}

function RegisterForm() {
  const [values, setValues] = useState({ name: "", email: "", password: "" });
  const [touched, setTouched] = useState({});
  const [success, setSuccess] = useState(false);

  const errors = validate(values);
  const isValid = Object.keys(errors).length === 0;

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

  function handleBlur(event) {
    setTouched({ ...touched, [event.target.name]: true });
  }

  function handleSubmit(event) {
    event.preventDefault();
    setTouched({ name: true, email: true, password: true });
    if (isValid) {
      setSuccess(true);
    }
  }

  function field(name, label, type = "text") {
    const showError = touched[name] && errors[name];

    return (
      <div>
        <label htmlFor={name}>{label}</label>
        <input
          id={name}
          name={name}
          type={type}
          value={values[name]}
          onChange={handleChange}
          onBlur={handleBlur}
          aria-invalid={showError ? "true" : "false"}
          aria-describedby={showError ? `${name}-error` : undefined}
        />
        {showError && (
          <p id={`${name}-error`} className="error">
            {errors[name]}
          </p>
        )}
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} noValidate>
      {field("name", "Name")}
      {field("email", "Email", "email")}
      {field("password", "Password", "password")}
      <button type="submit">Register</button>
      {success && <p role="status">Account created!</p>}
    </form>
  );
}

export default RegisterForm;

Add a little CSS (for example in src/index.css) so errors stand out:

.error {
  color: #d93025;
  margin: 4px 0 12px;
  font-size: 0.9rem;
}

How it behaves in the browser

Walk through these steps:

  1. Press Register on the empty form. Every field becomes touched, and the page shows all three messages: Name must be at least 2 characters., Enter a valid email address. and Password must be at least 8 characters. No success message appears.
  2. Type Aisha, [email protected] and secret123. Each message disappears as soon as its field becomes valid.
  3. Press Register again. There are no errors, so Account created! appears.
  4. Type another letter in any field. The success message disappears, because handleChange calls setSuccess(false).

Understanding the new parts

  • touched[name] && errors[name]: show the error only if the field was touched and it has an error. This is && from the conditional rendering lesson.
  • handleSubmit: marks every field as touched, so all errors become visible, and only sets success when isValid is true.
  • field(...): a plain helper function that returns the JSX for one labelled input with its error. It saves us from repeating the same markup three times. (Later you can turn it into its own component.)
  • noValidate on the form: turns off the browser’s own pop-up messages, so that your messages are shown instead. Without it, an <input type="email"> would show the browser’s tooltip first. See the HTML form validation lesson for the built-in attributes required, minlength and pattern.

Make errors accessible

Colour alone is not enough. People who use screen readers need to hear what is wrong. Three small attributes make a big difference (see accessibility basics and ARIA basics):

Attribute What it does
<label htmlFor> Connects the text to the input, so it is read aloud
aria-invalid="true" Tells assistive technology the field has an error
aria-describedby="email-error" Connects the input to the error message, so the message is read with the field
role="status" on the success message Makes screen readers announce the message when it appears

In the form above, these are set up for you: the error paragraph has id="email-error" and the input points to it with aria-describedby. The id values match because both are built from the same name.

Should I disable the submit button?

Many forms disable the button until the form is valid. This looks tidy but causes problems: the user does not know why it is disabled, and people using keyboards or screen readers cannot even reach a disabled button to find out. A better habit is to keep the button enabled, and show clear errors when it is pressed, exactly as we did here.

Common mistakes

1. Storing errors in state. They can be calculated from the values. Extra state can get out of sync and cause bugs.

2. Showing every error immediately. An empty form full of red text feels hostile. Show errors after the field is touched or after a submit.

3. Forgetting to validate on submit. A user can press the button without touching any field. Mark all fields as touched and check again.

4. Not stopping the submit when invalid. If handleSubmit does not check isValid, invalid data goes through.

5. Relying only on client-side validation. Always validate again on the server before saving data.

6. Vague messages. Invalid does not help. Say what is expected: Password must be at least 8 characters.

7. Relying on colour only. Add text messages and aria attributes so everyone can understand the errors.

8. Mismatched id and aria-describedby. If they do not match exactly, assistive technology cannot connect the message to the field.

9. Trusting a clever regular expression for emails. Keep the pattern simple and friendly, and let the server confirm by sending an email.

Practice

  1. Write a validate(values) function for a form with name and age. The name must have at least 2 characters, and the age must be a number between 18 and 100. Return an object of error messages. Test it with a few sample values in the console.

  2. Build the RegisterForm from this lesson and test the four steps from the “How it behaves” section.

  3. Predict, then check: In the form from this lesson, what happens if you type a valid name and then click directly on the Register button with the other fields empty? Which messages appear?

  4. Add a confirm password field. It must match the password. Show Passwords do not match. otherwise.

  5. Add a phone number field that must contain exactly 10 digits (hint: /^\d{10}$/). Show a helpful message.

  6. Debug: The user presses Register on an empty form and nothing happens: no errors are shown. Why, and how do you fix it?

    function handleSubmit(event) {
      event.preventDefault();
      if (isValid) {
        setSuccess(true);
      }
    }
  7. Debug: A screen reader user says they do not hear the error text when they focus the password field. Which attribute is probably missing or wrong?

  8. Add a Show password checkbox that toggles the password input between type="password" and type="text" using state.

Recap

  • Write a plain validate(values) function that returns an object of error messages.
  • Calculate errors on every render. Do not store them in state.
  • Track which fields were touched (with onBlur), and show an error only for touched fields. On submit, mark all fields as touched.
  • Only continue with the submit when Object.keys(errors).length === 0.
  • Use noValidate when you want your own messages instead of the browser’s pop-ups.
  • Make errors accessible with label, aria-invalid, aria-describedby and role="status".
  • Client-side validation helps users. The server must always validate again.
  • Next, you will build a complete first project that combines everything you learned.

Frequently asked questions

Should I validate on change, on blur or on submit?

A good default is on blur (when the user leaves a field) plus on submit. Validating on every keystroke can feel aggressive, because users see errors while they are still typing. Fields like passwords with a live strength hint are a good exception.

Should I use the browser's built-in validation or my own?

You can use both. Attributes such as required and type="email" are quick and accessible. Custom validation gives you full control over messages and timing. Add noValidate to the form if you want only your own messages to show.

Is client-side validation enough?

No. It improves the experience, but anyone can send data to your server without using your form. The server must always check the data again before saving it.

Why not store the errors in state?

Because they can be calculated from the form values. Storing them means you must remember to update them in several places, and they can fall out of sync with the values. A function that computes them on every render is simpler and safer.

Is there a library for validation?

Yes, there are popular libraries for forms and validation. They are useful in large projects. Learn the basics first, as in this lesson, so you understand what the libraries do. We do not need any extra package for this course.

Why does the success message disappear when I type?

In this example, handleChange calls setSuccess(false), because the data is no longer the submitted version after the user changes a field. You can remove that line if you prefer the message to stay visible.

See also: React Forms and Controlled Inputs, JavaScript Form Validation, HTML Form Validation, HTML Accessibility Basics