← Back to Chapters

Validation Basics

✅ Validation Basics

⚛️ React ? Forms ?️ Validation

? Quick Overview

Form validation ensures that user input meets expected criteria before submission. In React, validation can be implemented manually using component state and conditional rendering, or with helper libraries like Yup and Formik.

In this topic, you’ll learn how to implement:

  • Required field checks (e.g., name must not be empty).
  • Email format validation using regex.
  • Password strength checks using length rules.
  • Real-time (live) validation while the user types.

? Key Concepts

  • Required Fields – Ensure no essential fields are left empty.
  • Pattern Matching – Validate formats like email addresses or phone numbers.
  • Range Checks – Verify numeric input (e.g., age or price limits).
  • Custom Rules – Implement domain-specific validation based on business needs.
  • Live Validation – Provide real-time feedback as the user types.

? Syntax & Theory

React validation usually follows a simple pattern:

  1. Store form values and error messages in useState hooks.
  2. Write validation logic inside event handlers (e.g., onSubmit or onChange).
  3. Update error state when validation fails.
  4. Conditionally render error messages under the related input fields.
  5. Optionally block form submission until all errors are resolved.

Libraries like Yup and Formik help manage complex validation and reduce boilerplate, but understanding manual validation with React state is the essential first step.

? Basic Required Field Validation

The simplest validation checks whether a required field has been filled in before allowing the form to submit. If the input is empty, an error message appears; otherwise, the form is accepted.

? View Code Example
// Validate that the name field is not empty before submitting
import React, { useState } from "react";

function RequiredFieldForm() {
  const [name, setName] = useState("");
  const [error, setError] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    if (name.trim() === "") {
      setError("Name is required!");
    } else {
      setError("");
      alert("Form submitted successfully!");
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <h4>Required Field Example</h4>
      <input
        type="text"
        className="form-control mb-2"
        placeholder="Enter your name"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      {error && <p className="text-danger">{error}</p>}
      <button className="btn btn-primary">Submit</button>
    </form>
  );
}

export default RequiredFieldForm;

? What Happens?

  • When the user clicks Submit, handleSubmit prevents the default form action.
  • If name.trim() is empty, an error message "Name is required!" is shown.
  • If the input is valid, the error is cleared and a success alert appears.

? Email Format Validation

You can validate email addresses using regular expressions (regex) to ensure they follow a valid pattern like username@domain.com.

? View Code Example
// Validate email using a regular expression before submission
import React from "react";

function EmailValidationForm() {
  const [email, setEmail] = React.useState("");
  const [error, setError] = React.useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      setError("Please enter a valid email address!");
    } else {
      setError("");
      alert("Valid email submitted!");
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <h4>Email Validation Example</h4>
      <input
        type="email"
        className="form-control mb-2"
        placeholder="Enter email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      {error && <p className="text-danger">{error}</p>}
      <button className="btn btn-success">Validate</button>
    </form>
  );
}

export default EmailValidationForm;

? Output & Behaviour

  • emailRegex checks that the input contains text, an @, and a valid domain part.
  • If the pattern does not match, a helpful error message is shown under the input.
  • If the pattern matches, the error is cleared and a success alert confirms the email.

? Password Strength Validation

Passwords are often validated using rules like minimum length, presence of uppercase letters, digits, or special characters. Here we start with a basic length check.

? View Code Example
// Ensure the password is strong enough before accepting it
import React from "react";

function PasswordValidationForm() {
  const [password, setPassword] = React.useState("");
  const [error, setError] = React.useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    if (password.length < 8) {
      setError("Password must be at least 8 characters long!");
    } else {
      setError("");
      alert("Strong password!");
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <h4>Password Validation Example</h4>
      <input
        type="password"
        className="form-control mb-2"
        placeholder="Enter password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      {error && <p className="text-danger">{error}</p>}
      <button className="btn btn-warning">Check Password</button>
    </form>
  );
}

export default PasswordValidationForm;

? Output & Behaviour

  • If the user enters fewer than 8 characters, an error message explains the requirement.
  • Once the password is 8 or more characters, the error is cleared.
  • You can later extend this with checks for uppercase letters, digits, and symbols.

⚙️ Real-Time (Live) Validation

Validation doesn’t have to happen only on submit. You can validate as the user types and display instant feedback about whether the current value is valid.

? View Code Example
// Provide instant feedback while the user types a username
import React from "react";

function LiveValidationForm() {
  const [username, setUsername] = React.useState("");
  const [error, setError] = React.useState("");

  const validate = (value) => {
    if (value.length < 4) return "Username must be at least 4 characters!";
    return "";
  };

  const handleChange = (e) => {
    const value = e.target.value;
    setUsername(value);
    setError(validate(value));
  };

  return (
    <div>
      <h4>Live Validation Example</h4>
      <input
        type="text"
        className="form-control mb-2"
        placeholder="Enter username"
        value={username}
        onChange={handleChange}
      />
      {error ? (
        <p className="text-danger">{error}</p>
      ) : (
        username && <p className="text-success">Looks good!</p>
      )}
    </div>
  );
}

export default LiveValidationForm;

⚡ Live Feedback

  • As the user types, handleChange updates both username and error.
  • If the username is too short, an error message appears immediately.
  • If it meets the requirement, a positive message "Looks good!" is shown instead.

? Tips & Best Practices

  • Show validation messages only after the user interacts with the field (blur or first change).
  • Use regular expressions for pattern-based validation such as email or phone numbers.
  • Keep validation logic simple and modular by using helper functions like validate().
  • Use aria-invalid and aria-describedby on inputs to improve accessibility.
  • Display clear, human-friendly error messages that explain how to fix the problem.

? Try It Yourself

  1. Create a form with Name, Email, and Password fields.
  2. Validate that all fields are filled before submission.
  3. Ensure the email follows a valid format using a regex.
  4. Display live password strength feedback (weak / medium / strong) as the user types.
  5. Disable the submit button until all fields pass validation.

Goal: Practice implementing client-side validation using React state so that users can submit only accurate and complete data.