Check a form before accepting it

Stop a form from sending, and tell the person what is wrong.

What to build

A form handler that checks an email address and shows a message.

Requirements

  • Submitting the form must not reload the page.
  • Trim the email. If it is empty, or has no @, set #message to Please enter a valid email and give it the class error.
  • Otherwise, set #message to Thanks, EMAIL, remove the class error, and empty the box.

Constraints

Listen for submit on the form, not for click on the button, so that the Enter key works too.

Example

An input of mitu@example.com shows Thanks, mitu@example.com.

Why it works

Without preventDefault, the browser would leave the page and your message would be lost. Checking in the browser gives instant help, but a real server must always check again, because a browser's checks can be bypassed.

Hints

Hint 1

Listen for submit on the form, and call event.preventDefault() first.

Hint 2

input.value.trim() removes spaces around the text.

Hint 3

classList.toggle("error", isBad) adds or removes the class according to a condition.

Solution

Show one correct solution (try it yourself first)
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Sign up</title>
  <style>
    .error { color: firebrick; }
  </style>
</head>
<body>
  <form id="signup" novalidate>
    <label for="email">Email</label>
    <input id="email" type="text" autocomplete="email">
    <button>Sign up</button>
  </form>
  <p id="message" role="status"></p>
  <script>
    const form = document.querySelector("#signup");
    const input = document.querySelector("#email");
    const message = document.querySelector("#message");

    form.addEventListener("submit", (event) => {
      event.preventDefault();
      const email = input.value.trim();
      const bad = email === "" || !email.includes("@");
      message.classList.toggle("error", bad);
      if (bad) {
        message.textContent = "Please enter a valid email";
      } else {
        message.textContent = "Thanks, " + email;
        input.value = "";
      }
    });
  </script>
</body>
</html>

Lesson: Events and forms →