Lesson 82 +30 XP

Project 4: Form Validation

Project 4: Form Validation

Validate a form before it is submitted, and show errors to the user.

Step 1: The HTML

<form id="myForm">
  <input id="email" placeholder="Email">
  <input id="age" placeholder="Age">
  <button type="submit">Submit</button>
</form>
<p id="error"></p>

Step 2: The JavaScript

const form = document.getElementById("myForm");
const errorEl = document.getElementById("error");

form.addEventListener("submit", function(event) {
  event.preventDefault();

  const email = document.getElementById("email").value;
  const age = document.getElementById("age").value;

  if (!email.includes("@")) {
    errorEl.textContent = "Enter a valid email.";
    return;
  }
  if (Number(age) < 18) {
    errorEl.textContent = "You must be at least 18.";
    return;
  }

  errorEl.textContent = "Valid! Submitting...";
});

Step 3: How it works

  • preventDefault() stops the page from reloading.
  • Read inputs with .value.
  • Check the data with includes() and Number().
  • Show errors in a message element.

Step 4: Try it

Submit an invalid form and see the error messages appear.

Bonus ideas

  • Validate a password length.
  • Highlight invalid fields with a class.
  • Clear the error when the user fixes the input.

TL;DR

  • event.preventDefault stops form reloads.
  • Input values come as strings, convert when needed.
  • Validate before accepting data.
  • Show clear error messages.