Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS

Basic JavaScript

JS Tutorial JS Introduction JS Where To JS Output

JS Syntax

JS Syntax JS Statements JS Comments JS Variables JS Let JS Const JS Types

JS Operators

JS Operators JS Arithmetic JS Assignment JS Comparisons JS Conditional JS If JS If Else JS Ternary JS Switch JS Booleans JS Logical

JS Loops

JS Loops JS Loop for JS Loop while JS Break JS Continue JS Control Flow

JS Strings

JS Strings JS String Templates JS String Methods JS String Search JS String Reference

JS Numbers

JS Numbers JS Number Methods JS Number Properties JS Number Reference JS Bitwise JS BigInt

JS Functions

Function Path Function Intro Function Invocation Function Parameters Function Returns Function Arguments Function Expressions Function Arrow Function Quiz

JS Objects

Object Path Object Intro Object Properties Object Methods Object this Object Display Object Constructors

JS Scope

JS Scope JS Code Blocks JS Hoisting JS Strict Mode

JS Dates

JS Dates JS Date Formats JS Date Get JS Date Set JS Date Methods

JS Arrays

JS Arrays JS Array Methods JS Array Search JS Array Sort JS Array Iterations JS Array Reference JS Array Const

JS Sets

JS Sets JS Set Methods JS Set Logic JS Set WeakSet JS Set Reference

JS Maps

JS Maps JS Map Methods JS Map WeakMap JS Map Reference

JS Iterations

JS Loops JS Iterables JS Iterators JS Generators

JS Math

JS Math JS Math Reference JS Math Random

JS RexExp

JS RegExp JS RegExp Flags JS RegExp Classes JS RegExp Metachars JS RegExp Assertions JS RegExp Quantifiers JS RegExp Patterns JS RegExp Objects JS RegExp Methods

JS Data Types

JS Destructuring JS Data Types JS Primitive Data JS Object Types JS typeof JS toString JS Type Conversion

JS Errors

JS Errors Intro JS Errors Silent JS Error Statements JS Error Object

JS Debugging

Debugging Intro Debugging Console Debugging Breakpoints Debugging Errors Debugging Async Debugging Reference

JS Conventions

JS Style Guide JS Best Practices JS Mistakes JS Performance

JS References

JS Statements JS Reserved Keywords JS Operators JS Precedence

JS Versions

JS 2026 JS 2025 JS 2024 JS 2023 JS 2022 JS 2021 JS 2020 JS 2019 JS 2018 JS 2017 JS 2016 JS Versions JS 2015 (ES6) JS 2009 (ES5) JS 1999 (ES3) JS IE / Edge JS History

JS HTML

JS HTML DOM JS Events JS Projects New

JS Advanced

JS Temporal  New JS Functions JS Objects JS Classes JS Asynchronous JS Modules JS Meta & Proxy JS Typed Arrays JS DOM Navigation JS Windows JS Web APIs JS AJAX JS JSON JS jQuery JS Graphics JS Examples JS Reference


Project - Form Validation

In this project you will build a form with validation.

The form will show error messages under each input field, and it will not submit until everything is valid.

What You Will Learn

  • How to validate form fields with JavaScript
  • How to prevent a form from submitting
  • How to show error messages under inputs
  • How to check email and password rules

Step 1 - Create the HTML

Create a form with four fields and an error message under each field.

Example

<form id="signupForm">

<div class="field">
  <label>Name:</label><br>
  <input id="name" type="text" placeholder="Your name">
  <p id="nameError" class="error"></p>
</div>

<form>
Try it Yourself »

Step 2 - Add the CSS

Example

<style>
input {
  padding: 8px;
  width: 260px;
  margin-bottom: 4px;
}
.error {
  color: red;
  margin: 0;
}
.ok {
  color: green;
  margin: 0;
}
.field {
  margin-bottom: 12px;
}
</style>
Try it Yourself »

Step 3 - Add JavaScript

You must create an object for each field.

Example

// Create an Object for each Field
const form = document.getElementById("signupForm");
const nameInput = document.getElementById("name");
const emailInput = document.getElementById("email");
const passInput = document.getElementById("password");
const confirmInput = document.getElementById("confirm");
const nameError = document.getElementById("nameError");
const emailError = document.getElementById("emailError");
const passError = document.getElementById("passwordError");
const confirmError = document.getElementById("confirmError");
const result = document.getElementById("result");

You need a function to diplay errors.

Example

// Function to Display Error
function showError(el, message) {
  el.innerHTML = message;
}

You need a function to clear the error field.

Example

// Function to Clear the Error
function clearError(el) {
  el.innerHTML = "";
}

You need a function to validate the form.

Example

// Function to Validate Form
function validateForm() {
  return false;
}

You need the code to validate the form.

To validate the form, you must stop the page from reloading.

Example

// Prevent Default Reloading
form.addEventListener("submit", function (event) {
  event.preventDefault();

// Clear Result
  result.innerHTML = "";

// Validate Form
  if (validateForm()) {
    result.innerHTML = "Form is valid!";
    result.className = "ok";
  } else {
    result.innerHTML = "Please fix the errors.";
    result.className = "error";
  }
});
Try it Yourself »


Step 4 - Validate Fields

Create one function per field.

Validate Name

// Function to Validate Name
function validateName() {
  let value = nameInput.value.trim();
  if (value.length < 2) {
    showError(nameError, "Name must be at least 2 characters.");
    return false;
  }
  clearError(nameError);
  return true;
}

// Function to Validate Form
function validateForm() {
  let okName = validateName();
  return okName;
}
Try it Yourself »

Validate Email

// Function to Validate Email
function validateEmail() {
  let value = emailInput.value.trim();
  if (!(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value))) {
    showError(emailError, "Enter a valid email address.");
    return false;
  }
  clearError(emailError);
  return true;
}

// Function to Validate Form
function validateForm() {
  let okName = validateName();
  let okEmail = validateEmail();
  return okName && okEmail;
}
Try it Yourself »

Validate Password

// Function to Validate Password
function validatePassword() {
  let value = passInput.value;
  if (value.length < 8) {
    showError(passError, "Password must be at least 8 characters.");
    return false;
  }
  clearError(passError);
  return true;
}

// Function to Validate Form
function validateForm() {
  let okName = validateName();
  let okEmail = validateEmail();
  let okPass = validatePassword();
  return okName && okEmail && okPass;
}
Try it Yourself »

Validate Confirm

// Function to Validate Confirm
function validateConfirm() {
  let pass = passInput.value;
  let confirm = confirmInput.value;
  if (confirm === "") {
    showError(confirmError, "Please confirm your password.");
    return false;
  }
  if (confirm !== pass) {
    showError(confirmError, "Passwords do not match.");
    return false;
  }
  clearError(confirmError);
  return true;
}

// Function to Validate Form
function validateForm() {
  let okName = validateName();
  let okEmail = validateEmail();
  let okPass = validatePassword();
  let okConfirm = validateConfirm();
  return okName && okEmail && okPass && okConfirm;
}
Try it Yourself »

Form Validation (Finished)

This example shows the finished project.

The CSS

<style>
input {
  padding: 8px;
  width: 260px;
  margin-bottom: 4px;
}
.error {
  color: red;
  margin: 0;
}
.ok {
  color: green;
  margin: 0;
}
.field {
  margin-bottom: 12px;
}
</style>

The HTML

<!DOCTYPE html>
<html>
<style>
... CSS goes here
</style>

<body>
<h2>Sign Up</h2>

<form id="signupForm">

<div class="field">
  <label>Name:</label><br>
  <input id="name" type="text" placeholder="Your name">
  <p id="nameError" class="error"></p>
</div>

<div class="field">
  <label>Email:</label><br>
  <input id="email" type="text" placeholder="name@example.com">
  <p id="emailError" class="error"></p>
</div>

<div class="field">
  <label>Password:</label><br>
  <input id="password" type="password" placeholder="Min 8 characters">
  <p id="passwordError" class="error"></p>
</div>

<div class="field">
  <label>Confirm Password:</label><br>
  <input id="confirm" type="password" placeholder="Repeat password">
  <p id="confirmError" class="error"></p>
</div>

<p><button type="submit">Create Account</button></p>

</form>

<p id="result"></p>

<script>
// JavaScript goes here
</script>

</body>
</html>

The JavaScript

// Create an Object for each Field
const form = document.getElementById("signupForm");
const nameInput = document.getElementById("name");
const emailInput = document.getElementById("email");
const passInput = document.getElementById("password");
const confirmInput = document.getElementById("confirm");
const nameError = document.getElementById("nameError");
const emailError = document.getElementById("emailError");
const passError = document.getElementById("passwordError");
const confirmError = document.getElementById("confirmError");
const result = document.getElementById("result");

// Function to Display Error
function showError(el, message) {
  el.innerHTML = message;
}

// Function to Clear Error
function clearError(el) {
  el.innerHTML = "";
}

// Function to Validate Name
function validateName() {
  let value = nameInput.value.trim();
  if (value.length < 2) {
    showError(nameError, "Name must be at least 2 characters.");
    return false;
  }
  clearError(nameError);
  return true;
}

// Function to Validate Email
function validateEmail() {
  let value = emailInput.value.trim();
  if (!(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value))) {
    showError(emailError, "Enter a valid email address.");
    return false;
  }
  clearError(emailError);
  return true;
}

// Function to Validate Password
function validatePassword() {
  let value = passInput.value;
  if (value.length < 8) {
    showError(passError, "Password must be at least 8 characters.");
    return false;
  }
  clearError(passError);
  return true;
}

// Function to Validate Confirm
function validateConfirm() {
  let pass = passInput.value;
  let confirm = confirmInput.value;
  if (confirm === "") {
    showError(confirmError, "Please confirm your password.");
    return false;
  }
  if (confirm !== pass) {
    showError(confirmError, "Passwords do not match.");
    return false;
  }
  clearError(confirmError);
  return true;
}

// Function to Validate Form
function validateForm() {
  let okName = validateName();
  let okEmail = validateEmail();
  let okPass = validatePassword();
  let okConfirm = validateConfirm();
  return okName && okEmail && okPass && okConfirm;
}

// Prevent Default Reloading
form.addEventListener("submit", function (event) {
  event.preventDefault();

// Clear Result
  result.innerHTML = "";

// Validate Form
  if (validateForm()) {
    result.innerHTML = "Form is valid!";
    result.className = "ok";
  } else {
    result.innerHTML = "Please fix the errors.";
    result.className = "error";
  }
});
Try it Yourself »

Common Mistakes

  • Forgetting event.preventDefault()
  • Not trimming the input values
  • Using innerHTML with user input (use text only for messages)

Exercises

Exercise 1

Add a rule that the password must contain at least one number.

Exercise 2

Validate fields while the user is typing (use the input event).

Exercise 3

Show a green message next to fields that are valid.


Bonus Challenges (Level Up)

  • Add password strength indicator (Weak / Medium / Strong)
  • Disable the submit button until everything is valid
  • Show/hide password button

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.

-->