mc0de
JavaScript · Lesson 13 of 17

Form Validation

Build smarter, friendlier forms! Learn how to check required fields, validate email addresses, verify passwords, and guide visitors toward successful submissions.

Required Fields Email Checks Password Rules Error Messages
● ● ●   validation.js
const email =
  document.getElementById(
    "email"
  );

if (email.validity.valid) {
  console.log("Valid email!");
}
LIVE EMAIL VALIDATOR
Enter an email address to test it.
01 / Getting Started

What Is Form Validation?

Forms appear everywhere: registration pages, contact forms, login screens, and online applications. Before accepting the information someone enters, a website should check whether it meets the expected requirements.

This process is called form validation. Validation can identify missing information, incorrectly formatted values, and entries that don’t match.

A basic HTML form
<form id="signupForm">
  <label for="email">Email address</label>
  <input id="email" type="email" required>

  <button type="submit">Sign Up</button>
</form>

The browser already understands some validation rules. Here, required means the field cannot be empty, and type="email" asks the browser to check for a basic email-address format.

Important: Client-side validation improves the visitor’s experience, but it is not a security boundary. A real application must validate submitted data again on the server.
02 / Required Fields

Check That Visitors Enter Something

One of the most common validation tasks is ensuring that required information isn’t missing. JavaScript can read an input’s value and check whether it contains meaningful text.

Checking a name field
const nameInput = document.getElementById("name");

const name = nameInput.value.trim();

if (name === "") {
  console.log("Please enter your name.");
} else {
  console.log("Hello, " + name + "!");
}

The trim() method removes whitespace from both ends. Without it, someone could enter only spaces and pass a simple nonempty check.

Example
Input: ” ” Result: Please enter your name. Input: “Alex” Result: Hello, Alex!

HTML’s required attribute provides a useful first layer. JavaScript lets you customize the messages and handle more specific rules.

03 / Email Validation

Check Email Address Formatting

An email field should contain an address in a recognizable format. The browser can perform a basic syntax check when an input uses type="email".

Using the browser’s validity API
const email = document.getElementById("email");

if (email.validity.valueMissing) {
  console.log("Email is required.");
} else if (email.validity.typeMismatch) {
  console.log("Enter a valid email address.");
} else {
  console.log("Email format accepted.");
}

The validity property exposes several useful checks. valueMissing detects a missing required value, and typeMismatch identifies a value that doesn’t meet the input type’s basic formatting rules.

Keep in mind: Passing email-format validation doesn’t prove that an address exists or belongs to the visitor. That generally requires an email verification process.
04 / Password Requirements

Validate Password Rules

Registration forms often require passwords to meet specific conditions. JavaScript can check those conditions and provide immediate feedback.

Checking a minimum length
const password = document.getElementById("password").value;

if (password.length < 8) {
  console.log("Use at least 8 characters.");
} else {
  console.log("Minimum length met.");
}

For this learning exercise, we’ll use a minimum of eight characters. Real applications should follow their own security requirements, encourage longer passwords, and support password managers.

To check that two password fields match, compare their values:

Confirming a password
const password = document.getElementById("password").value;
const confirm = document.getElementById("confirm").value;

if (password !== confirm) {
  console.log("Passwords do not match.");
}
Security note: Never display someone’s password in an error message, log it, or store it in browser local storage. This lesson’s demo does not transmit or save passwords.
05 / Displaying Helpful Errors

Guide Visitors Toward a Solution

Good validation should do more than say something is wrong. It should explain what needs to be corrected.

Instead of a generic “Invalid form” message, show specific feedback near the affected field.

Displaying an error message
const input = document.getElementById("username");
const error = document.getElementById("usernameError");

if (input.value.trim() === "") {
  error.textContent = "Please enter a username.";
  input.setAttribute("aria-invalid", "true");
} else {
  error.textContent = "";
  input.removeAttribute("aria-invalid");
}

Using textContent ensures that the message is displayed as text. The aria-invalid attribute helps communicate invalid field states to assistive technologies.

Helpful vs. unhelpful feedback
Unhelpful: Something went wrong. Helpful: Your password must contain at least 8 characters.

Connect each error message to its input with aria-describedby so the relationship is accessible.

06 / Handling Submission

Prevent Invalid Form Submissions

Remember the submit event from Lesson 12? We can use it to check every field before proceeding.

Validating when a form is submitted
const form = document.getElementById("signupForm");

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

  const name = document.getElementById("name").value.trim();

  if (!name) {
    console.log("Please enter your name.");
    return;
  }

  console.log("Demo form passed validation!");
});

preventDefault() keeps this demonstration on the same page. In a real application, successfully validated data would then be submitted through an appropriate, secure process.

You can also call checkValidity() to ask whether an HTML form meets its built-in validation constraints.

Checking browser validation rules
if (form.checkValidity()) {
  console.log("Browser validation passed.");
} else {
  console.log("Please correct the form.");
}
07 / Validation in Action

Try a Live Registration Form

Let’s bring everything together. Enter a name, email, and password below. The demonstration checks the fields and displays a success message only when they meet the example requirements.

Live Registration Validator
This is a local demonstration. No account will be created.

Try submitting the form empty, entering an invalid email, using a short password, or entering two different passwords. Then correct the values and submit again.

Good design: Show errors near the relevant fields, preserve entered information when validation fails, and give visitors a clear way to correct mistakes.
🚀 mC0de Challenge

Build a Smart Registration Form

Create a registration form that checks user input and guides visitors through correcting mistakes.

Your Mission

  1. Create fields for full name, email, password, and password confirmation.
  2. Make sure the name and email are not empty.
  3. Use type="email" and the browser’s validity API to check email formatting.
  4. Require a password containing at least eight characters.
  5. Check that the password and confirmation match.
  6. Display specific error messages next to invalid fields.
  7. Prevent submission and display a success message when every rule passes.
Extra challenge: Add live validation, a password-strength indicator, and a checkbox requiring visitors to acknowledge the demo’s terms.
💻 Interactive JavaScript Sandbox

Build Your Smart Registration Form!

Edit the starter code and test your validation rules. The Load Solution button adds live field feedback, a password-strength indicator, confirmation matching, and a terms checkbox.

Live Result
Lesson 13 Recap

What You’ve Learned

You’re Building Smarter Forms!

You now know how to check input, prevent invalid submissions, and guide visitors with clear validation messages.

  • Understand why form validation matters.
  • Check required fields using trim().
  • Use HTML email validation and the validity API.
  • Validate password length and confirmation fields.
  • Display accessible, field-specific error messages.
  • Handle form submissions with preventDefault().
  • Build a Smart Registration Form with JavaScript.

Next up: JSON — learn how JavaScript applications organize and exchange structured information!

Your Learning Journey

0 / 17 Completed

Lesson 13 of 17 — you’re getting closer to the final project!

🎉

You've Mastered Form Validation Basics!

You can now check required fields, validate email formats, compare passwords, and display helpful error messages. You've also built your own Smart Registration Form!