Java Script
Back Next

JavaScript Form Validation


Form validation is the process of checking whether the information a user enters into a form is correct and complete before sending it to the server.

For example:

  • Is the email written in a valid format?
  • Is the password long enough?
  • Did the user leave a required field empty?

JavaScript form validation happens in the browser, before the form is submitted. This gives users instant feedback and improves user experience.


Types of Form Validation

There are two main types:

1️⃣ HTML Built-in Validation

HTML5 provides built-in validation using attributes like:

  • required
  • minlength
  • maxlength
  • pattern
  • type="email"

Example:

<input type="email" required>

The browser automatically checks if the input looks like an email.


2️⃣ JavaScript Custom Validation

JavaScript allows you to:

  • Create custom rules
  • Show custom error messages
  • Prevent form submission manually

This gives you full control.


Basic Example: HTML Form

Here is a simple form:

<form id="myForm">
  <label>Name:</label>
  <input type="text" id="name">
  
  <label>Email:</label>
  <input type="text" id="email">
  
  <label>Password:</label>
  <input type="password" id="password">
  
  <button type="submit">Submit</button>
</form>

<p id="errorMessage" style="color:red;"></p>


Step-by-Step JavaScript Validation

Access the Form

We select the form using JavaScript:

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

Listen for Form Submission

We prevent the form from submitting immediately:

form.addEventListener("submit", function(event) {
  event.preventDefault(); // Stops form from submitting
  
  // Validation code will go here
});

event.preventDefault() stops the form from refreshing the page.

Get Input Values

const name = document.getElementById("name").value;
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;

Create Validation Rules

✅ Rule 1: Name Cannot Be Empty

if (name === "") {
  errorMessage.textContent = "Name is required.";
  return;
}

✅ Rule 2: Email Format Check

We use a regular expression (RegEx) to check email format:

const emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;

if (!email.match(emailPattern)) {
  errorMessage.textContent = "Please enter a valid email address.";
  return;
}

Explanation of the pattern:

  • @ must exist
  • . must exist after @
  • 2–3 letters at the end (like .com, .org)

✅ Rule 3: Password Length

if (password.length < 6) {
  errorMessage.textContent = "Password must be at least 6 characters long.";
  return;
}

If Everything Is Valid

errorMessage.textContent = "Form submitted successfully!";


Why Use JavaScript Validation?

✔ Instant feedback

✔ Better user experience

✔ Reduces server load

✔ Prevents unnecessary submissions

⚠ Important:

Client-side validation is NOT secure alone.

You must also validate on the server.


Common Validation Techniques

Example: Confirm Password Match

if (password !== confirmPassword) {
  errorMessage.textContent = "Passwords do not match.";
  return;
}


Complete Working Example

Here is the full code combined:

Example Code:
<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Form Validation</title>
</head>
<body>

<form id="myForm">
  <label>Name:</label><br>
  <input type="text" id="name"><br><br>
  
  <label>Email:</label><br>
  <input type="text" id="email"><br><br>
  
  <label>Password:</label><br>
  <input type="password" id="password"><br><br>
  
  <button type="submit">Submit</button>
</form>

<p id="errorMessage" style="color:red;"></p>

<script>
const form = document.getElementById("myForm");
const errorMessage = document.getElementById("errorMessage");

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

  const name = document.getElementById("name").value;
  const email = document.getElementById("email").value;
  const password = document.getElementById("password").value;

  const emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;

  if (name === "") {
    errorMessage.textContent = "Name is required.";
    return;
  }

  if (!email.match(emailPattern)) {
    errorMessage.textContent = "Please enter a valid email address.";
    return;
  }

  if (password.length < 6) {
    errorMessage.textContent = "Password must be at least 6 characters long.";
    return;
  }

  errorMessage.style.color = "green";
  errorMessage.textContent = "Form submitted successfully!";
});
</script>

</body>
</html>
Java Script
Introduction Application of JavaScript Defining JavaScript Client-Side JavaScript JavaScript Syntax JavaScript Varaibles JavaScript Operators JavaScript Statements JavaScript Arrays Sorting JavaScript Array JavaScript Functions JavaScript Objects JavaScript Switch Case & While Loops JavaScript For & For-In Loops JavaScript Cookies JavaScript Form Validation JavaScript Error and Exception Handling JavaScript Animation
All Courses
Bootstrap Content Writing CSS Cyber Security Data Analysis Deep Learning Email Marketing Excel HTML Java Script Machine Learning MySQLi PHP Power Bi Python for Analysis SEO SMM SQL