Menu

React Form Validation: Rules, Errors & Examples

Form Validation Basics

Why Validate in React?

HTML has built-in validation like required and type="email," and you should keep using it. But React validation lets you show custom messages, validate as the user types, and block submission until the form is correct.

Example

src/components/LoginForm.jsx

jsx

import { useState } from "react";

function LoginForm() {
  const [formData, setFormData] = useState({ email: "", password: "" });
  const [errors, setErrors] = useState({});
  const [submitted, setSubmitted] = useState(false);

  function handleChange(event) {
    const { name, value } = event.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  }

  function validate() {
    const newErrors = {};

    if (!formData.email.trim()) {
      newErrors.email = "Email is required";
    } else if (!formData.email.includes("@")) {
      newErrors.email = "Enter a valid email address";
    }

    if (!formData.password) {
      newErrors.password = "Password is required";
    } else if (formData.password.length < 8) {
      newErrors.password = "Password must be at least 8 characters";
    }

    return newErrors;
  }

  function handleSubmit(event) {
    event.preventDefault();
    const newErrors = validate();
    setErrors(newErrors);

    if (Object.keys(newErrors).length === 0) {
      setSubmitted(true);
      setFormData({ email: "", password: "" });
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <input
          type="email"
          name="email"
          value={formData.email}
          onChange={handleChange}
          placeholder="Email"
        />
        {errors.email && <span className="error">{errors.email}</span>}
      </div>

      <div>
        <input
          type="password"
          name="password"
          value={formData.password}
          onChange={handleChange}
          placeholder="Password"
        />
        {errors.password && <span className="error">{errors.password}</span>}
      </div>

      <button type="submit">Log in</button>

      {submitted && <p className="success">Login successful</p>}
    </form>
  );
}

export default LoginForm;

How It Works

  • errors is a separate state object holding one message per invalid field.
  • validate() builds a fresh errors object and returns it. It does not set state itself, which keeps it easy to reason about.
  • Object.keys(newErrors).length === 0 checks whether the form passed.
  • {errors.email && <span>...</span>} shows the message only when that field has an error.
  • On success, the form clears itself by resetting formData.

Output

Submitting an empty form shows "Email is required" and "Password is required" under the respective fields. Fixing both and resubmitting shows the success message and clears the inputs.


ReactJS Tutorial

VA

Vishalini A



Learn via Video Course

React.js for Beginners: Build Modern Web Applications with React Logo

React.js for Beginners: Build Modern Web Applications with React

6 hrs



Get in Touch For Details