0
0
ReactHow-ToBeginner · 3 min read

How to Show Validation Errors in React Forms Easily

In React, show validation errors by storing error messages in state and conditionally rendering them near form inputs. Use event handlers like onChange or onSubmit to validate input and update error state dynamically.
📐

Syntax

To show validation errors in React, you typically:

  • Use useState to hold error messages.
  • Validate input values on events like onChange or onSubmit.
  • Update the error state with messages if validation fails.
  • Render error messages conditionally near the input fields.
jsx
const [errors, setErrors] = useState({});

function validate(values) {
  const errors = {};
  if (!values.email) {
    errors.email = 'Email is required';
  }
  return errors;
}

function handleSubmit(event) {
  event.preventDefault();
  const validationErrors = validate(formValues);
  setErrors(validationErrors);
  if (Object.keys(validationErrors).length === 0) {
    // proceed with form submission
  }
}

return (
  <form onSubmit={handleSubmit}>
    <input name="email" onChange={handleChange} />
    {errors.email && <div className="error">{errors.email}</div>}
    <button type="submit">Submit</button>
  </form>
);
💻

Example

This example shows a simple form with an email input. It validates that the email is not empty and shows an error message below the input if validation fails.

jsx
import React, { useState } from 'react';

export default function EmailForm() {
  const [email, setEmail] = useState('');
  const [errors, setErrors] = useState({});

  function validate(value) {
    const errors = {};
    if (!value.trim()) {
      errors.email = 'Email is required';
    } else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value)) {
      errors.email = 'Email is invalid';
    }
    return errors;
  }

  function handleChange(e) {
    setEmail(e.target.value);
    setErrors(validate(e.target.value));
  }

  function handleSubmit(e) {
    e.preventDefault();
    const validationErrors = validate(email);
    setErrors(validationErrors);
    if (Object.keys(validationErrors).length === 0) {
      alert('Form submitted with email: ' + email);
    }
  }

  return (
    <form onSubmit={handleSubmit} noValidate>
      <label htmlFor="email">Email:</label><br />
      <input
        id="email"
        name="email"
        type="email"
        value={email}
        onChange={handleChange}
        aria-describedby="email-error"
        aria-invalid={errors.email ? 'true' : 'false'}
      /><br />
      {errors.email && (
        <div id="email-error" style={{ color: 'red' }} role="alert">
          {errors.email}
        </div>
      )}
      <button type="submit">Submit</button>
    </form>
  );
}
Output
A form with an email input field. If the input is empty or invalid, a red error message appears below the input. On valid input and submit, an alert shows the entered email.
⚠️

Common Pitfalls

  • Not updating error state on every input change can cause stale error messages.
  • Showing errors only after submit can confuse users; validate on change or blur for better UX.
  • Forgetting to associate error messages with inputs using aria-describedby hurts accessibility.
  • Not preventing form submission when errors exist allows invalid data to submit.
jsx
/* Wrong: Errors not updated on input change, only on submit */
function handleSubmit(e) {
  e.preventDefault();
  const errors = validate(email);
  setErrors(errors);
  if (Object.keys(errors).length === 0) {
    // submit
  }
}

/* Right: Validate on input change too */
function handleChange(e) {
  setEmail(e.target.value);
  setErrors(validate(e.target.value));
}
📊

Quick Reference

  • Use useState to store errors as an object.
  • Validate inputs on onChange or onBlur for instant feedback.
  • Render error messages conditionally near inputs.
  • Use semantic HTML and ARIA attributes for accessibility.
  • Prevent form submission if errors exist.

Key Takeaways

Store validation errors in React state and update them on input events.
Show error messages conditionally near the related input fields.
Validate inputs on change or submit to provide timely feedback.
Use ARIA attributes like aria-describedby for accessible error messages.
Prevent form submission when validation errors exist.