Lesson 41 — Form Validation in React

🧭 Introduction

Form validation is one of the most important parts of any React application. Without proper validation, users can submit:

  • Empty fields
  • Invalid email addresses
  • Weak passwords
  • Incorrect data

React does not enforce validation automatically — you must handle it explicitly.

In this lesson, you will learn:

  • What form validation is
  • Client-side validation techniques
  • Validation using React state
  • Validation using React Hook Form
  • Best practices and common mistakes

❓ What is Form Validation?

Form validation means:

Ensuring user input meets specific rules before form submission.

Common validation rules:

  • Required fields
  • Minimum/maximum length
  • Email format
  • Password strength
  • Checkbox agreement

🧠 Why Form Validation is Important?

Without validation ❌

  • Bad data sent to backend
  • App crashes
  • Security risks
  • Poor user experience

With validation ✅

  • Clean data
  • Fewer errors
  • Better UX
  • Professional applications

🧩 Client-Side vs Server-Side Validation

TypePurpose
Client-sideInstant feedback
Server-sideFinal data verification

👉 Both are required in real apps.
This lesson focuses on client-side validation.


🛠 Method 1: Form Validation Using React State

This method uses controlled inputs + state.


📄 Example: Basic Validation

import { useState } from "react";

const RegisterForm = () => {
  const [email, setEmail] = useState("");
  const [error, setError] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!email) {
      setError("Email is required");
      return;
    }

    if (!email.includes("@")) {
      setError("Invalid email address");
      return;
    }

    setError("");
    alert("Form submitted");
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={email}
        placeholder="Email"
        onChange={(e) => setEmail(e.target.value)}
      />

      {error && <p style={{ color: "red" }}>{error}</p>}

      <button type="submit">Submit</button>
    </form>
  );
};

export default RegisterForm;


🧠 Limitations of State-Based Validation

❌ Too much code
❌ Hard to scale
❌ Complex for large forms

👉 This is why form libraries are preferred.


🛠 Method 2: Form Validation Using React Hook Form (Recommended)

React Hook Form makes validation simple and scalable.


📄 Required Field Validation

<input
  {...register("name", { required: "Name is required" })}
/>
{errors.name && <p>{errors.name.message}</p>}


📄 Email Validation Example

<input
  {...register("email", {
    required: "Email is required",
    pattern: {
      value: /^\S+@\S+$/i,
      message: "Invalid email format",
    },
  })}
/>
{errors.email && <p>{errors.email.message}</p>}


📄 Password Validation Example

<input
  type="password"
  {...register("password", {
    required: "Password required",
    minLength: {
      value: 6,
      message: "Minimum 6 characters",
    },
  })}
/>
{errors.password && <p>{errors.password.message}</p>}


🧩 Complete Validation Example

import { useForm } from "react-hook-form";

const LoginForm = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm();

  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        placeholder="Email"
        {...register("email", {
          required: "Email required",
          pattern: {
            value: /^\S+@\S+$/i,
            message: "Invalid email",
          },
        })}
      />
      {errors.email && <p>{errors.email.message}</p>}

      <input
        type="password"
        placeholder="Password"
        {...register("password", {
          required: "Password required",
          minLength: {
            value: 6,
            message: "Min 6 characters",
          },
        })}
      />
      {errors.password && <p>{errors.password.message}</p>}

      <button type="submit">Login</button>
    </form>
  );
};

export default LoginForm;


🧠 Built-in Validation Rules (React Hook Form)

RuleUsage
requiredMandatory field
minLengthMinimum characters
maxLengthMaximum characters
patternRegex validation
validateCustom validation

🧩 Custom Validation Example

<input
  {...register("age", {
    validate: (value) =>
      value >= 18 || "Age must be 18+",
  })}
/>
{errors.age && <p>{errors.age.message}</p>}


⚠ Common Validation Mistakes

❌ Not showing error messages
❌ Validating only on submit
❌ Hardcoding messages
❌ Ignoring accessibility


🎯 Best Practices for Form Validation

✅ Always show clear error messages
✅ Validate before submission
✅ Use form libraries for large forms
✅ Keep validation rules readable
✅ Combine client & server validation


❓ FAQs — Form Validation in React

🔹 Should I always validate forms?

Yes. Every form should have validation.


🔹 Is React Hook Form enough?

Yes, for most applications.


🔹 Can I validate while typing?

Yes, using mode: "onChange" in React Hook Form.


🔹 Where should validation logic live?

Inside form components or reusable hooks.


🧠 Quick Recap

✔ Form validation ensures clean input
✔ State-based validation works for small forms
✔ React Hook Form simplifies validation
✔ Error messages improve UX


🎉 Conclusion

Form validation is a non-negotiable skill for React developers. By mastering both basic validation and React Hook Form validation, you can build secure, user-friendly, and production-ready forms.

🎯 With this lesson, you have completed SECTION 8 — Forms & Validation successfully!


✅ Next Section Begins

SECTION 9 — Best Practices

👉 Next Lesson:
Lesson 42 — Folder Structure Best Practices

Leave a Comment