React: Validate a sign-up form

Check what the user entered and explain every problem at once.

What to build

A sign-up form with an email and a password, validated on submit.

Requirements

  • A form with controlled inputs: an input with the id email and an input with the id password and the type password, and a submit button.
  • On submit (without reloading), check: the email contains @ (Email must contain @) and the password has at least 8 characters (Password must be at least 8 characters).
  • If there are problems, show them as li items of a ul with the class errors, in that order. Otherwise show a p with the class success: Account created for EMAIL, and no errors.

Constraints

Validate only when the form is submitted.

Example

Submitting "ada" with "secret" lists both problems; submitting "ada@example.com" with "secret123" shows the success message.

Why it works

Collecting every problem in an array before showing them tells the user everything at once, and the state decides which of the two views to render.

Hints

Hint 1

Validate in handleSubmit and keep the list of errors in state.

Hint 2

Show the errors as a list, or the success message, depending on the state.

Solution

Show one correct solution (try it yourself first)
import { useState } from "react";

export default function App() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [errors, setErrors] = useState([]);
  const [done, setDone] = useState(false);

  function handleSubmit(event) {
    event.preventDefault();
    const problems = [];
    if (!email.includes("@")) problems.push("Email must contain @");
    if (password.length < 8) problems.push("Password must be at least 8 characters");
    setErrors(problems);
    setDone(problems.length === 0);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input id="email" value={email} onChange={(e) => setEmail(e.target.value)} />
      <input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
      <button type="submit">Sign up</button>
      {errors.length > 0 && (
        <ul className="errors">
          {errors.map((e) => (
            <li key={e}>{e}</li>
          ))}
        </ul>
      )}
      {done && <p className="success">Account created for {email}</p>}
    </form>
  );
}

Lesson: Forms and controlled inputs →