Lesson 9 of 10

Browser JavaScript

Lesson 9: Form Validation

Stop bad input before form submission and give clear feedback to users.

Learning Goals

Example

let form = document.getElementById("signupForm");
let emailInput = document.getElementById("email");

form.addEventListener("submit", function (event) {
  if (!emailInput.value.includes("@")) {
    event.preventDefault();
    alert("Enter a valid email");
  }
});
Good UX: show users what is wrong and how to fix it.

Practice

  1. Require username to be at least 3 characters.
  2. Require password to be at least 6 characters.
  3. Show custom messages under each field.

Homework

Create a registration form that validates name, email, and password before submitting.

Answer Guide
let form = document.getElementById("registerForm");
let nameInput = document.getElementById("name");
let emailInput = document.getElementById("email");
let passwordInput = document.getElementById("password");

form.addEventListener("submit", function (event) {
  if (nameInput.value.length < 2 || !emailInput.value.includes("@") || passwordInput.value.length < 6) {
    event.preventDefault();
    alert("Please complete the form correctly");
  }
});
← Previous Lesson Next Lesson →