Skip to content

Form with Validation

Medium ~30 min

What you'll build

A registration form with email and password fields that validate in real time. Shows error messages for invalid input and a success message on valid submission.

Goals

  • Build controlled form inputs
  • Validate input in real time as the user types
  • Prevent form submission with invalid data
  • Show and clear error messages

Prerequisites

  • Controlled components
  • Event handling
  • Conditional rendering

Steps

  1. 1

    Set up form state

    Create state for email, password, and errors object.

    Code
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [errors, setErrors] = useState({});

    Expected result

    Form state is ready.

  2. 2

    Add validation functions

    Create a validate function that checks email format and password length, returning an errors object.

    Code
    const validate = () => {
      const errs = {};
      if (!email.includes("@")) errs.email = "Invalid email";
      if (password.length < 8) errs.password = "Password must be 8+ characters";
      return errs;
    };

    Expected result

    Validation logic is ready to use.

  3. 3

    Build the form with controlled inputs and error display

    Render the form with controlled inputs. Show error messages below each field when errors exist.

    Code
    <form onSubmit={handleSubmit}>
      <input value={email} onChange={e => setEmail(e.target.value)} placeholder="Email" />
      {errors.email && <span>{errors.email}</span>}
      <input type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="Password" />
      {errors.password && <span>{errors.password}</span>}
      <button type="submit">Register</button>
    </form>

    Expected result

    Form fields update as you type, errors show when invalid.

  4. 4

    Handle form submission

    On submit, prevent default, run validation, and only proceed if there are no errors.

    Code
    const handleSubmit = (e) => {
      e.preventDefault();
      const errs = validate();
      if (Object.keys(errs).length > 0) {
        setErrors(errs);
      } else {
        setErrors({});
        alert("Registration successful!");
      }
    };

    Expected result

    Submitting with invalid data shows errors. Valid data shows success.

  5. 5

    Add state management & event handling

    Use useState to manage component state and add onClick/onChange handlers to interactive elements. State is the heart of React components, and event handling lets them respond to user actions.

    Code
    import { useState } from "react";
    
    export function MyComponent() {
      const [count, setCount] = useState(0);
      const [text, setText] = useState("");
    
      return (
        <div>
          <button onClick={() => setCount(c => c + 1)}>
            Count: {count}
          </button>
          <input
            value={text}
            onChange={(e) => setText(e.target.value)}
          />
        </div>
      );
    }

    Expected result

    Clicking the button increments the count; the input content updates in real time as you type.

Try it yourself

What you learned

You learned to build controlled forms with real-time validation in React: state holds input values, validation runs on submit, and conditional rendering shows errors. This pattern scales to complex forms.

Related Resources

Related Lessons

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic