Skip to main content
JavaScript Basics
CHAPTER 18 Beginner

JavaScript Forms Validation

Updated: May 12, 2026
30 min read

# JavaScript Forms Validation

Forms are the primary way users send data to your application. But users make mistakes. They forget passwords, type letters in phone number fields, and leave required fields blank.

In this chapter, we will learn how to intercept form submissions and validate the data using JavaScript before it ever reaches the server.

1. Introduction

HTML5 provides built-in validation attributes like required, minlength, and type="email". However, HTML validation is basic and looks different on every browser.

Using JavaScript for form validation allows you to:

  1. 1. Provide instant, real-time feedback as the user types.
  1. 2. Create completely custom, beautifully styled error messages.
  1. 3. Perform complex validation (e.g., checking if "Password" and "Confirm Password" match exactly).

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Intercept a form submission using preventDefault().
  • Validate required fields.
  • Compare two fields for equality (Password confirmation).
  • Understand the absolute basics of Regular Expressions (Regex) for email validation.
  • Display custom error messages on the DOM.
  • Build a complete Signup Form Validator mini-project.

3. The Validation Workflow

The standard workflow for JS validation is:

  1. 1. Listen for the form's submit event.
  1. 2. Call event.preventDefault() to stop the page from refreshing.
  1. 3. Grab the .value of every input field.
  1. 4. Run if/else logic to check if the values meet your rules.
  1. 5. If rules are broken, show error messages on the DOM and return (stop).
  1. 6. If all rules pass, proceed to send the data to the server (or show a success message).

---

4. Real-world Examples & Code Snippets

Example 1: Checking for Empty Fields

The most basic validation is ensuring a field is not empty after trim() removes accidental spaces.

javascript
12345678
// Example JavaScript
let username = document.getElementById("user").value.trim();

if (username === "") {
    console.log("Username cannot be empty!");
} else {
    console.log("Username is valid.");
}

Example 2: Checking String Length

Passwords usually require a minimum length.

javascript
123456
// Example JavaScript
let password = document.getElementById("pass").value;

if (password.length < 8) {
    console.log("Password must be at least 8 characters long.");
}

Example 3: Comparing Two Fields

A standard "Confirm Password" check.

javascript
1234567
// Example JavaScript
let pass1 = document.getElementById("pass1").value;
let pass2 = document.getElementById("pass2").value;

if (pass1 !== pass2) {
    console.log("Passwords do not match!");
}

Example 4: Checking for Numbers

If you need an age or phone number, ensure the input is not NaN (Not a Number).

javascript
12345678
// Example JavaScript
let ageStr = document.getElementById("age").value;
let ageNum = Number(ageStr);

// isNaN is a built-in JS function
if (isNaN(ageNum) || ageStr === "") {
    console.log("Please enter a valid number for age.");
}

Example 5: Real-time Validation (The input Event)

Validating while the user types provides excellent UX.

javascript
12345678910111213
// Example JavaScript
let passInput = document.getElementById("pass");
let helperText = document.getElementById("helper");

passInput.addEventListener("input", function() {
    if (passInput.value.length < 6) {
        helperText.textContent = "Weak";
        helperText.style.color = "red";
    } else {
        helperText.textContent = "Strong";
        helperText.style.color = "green";
    }
});

Example 6: Introduction to Regex (Regular Expressions)

Regex is a sequence of characters that forms a search pattern. It is incredibly powerful for validating complex strings like Emails.

javascript
12345678
// Example JavaScript
// A simple regex pattern to check if a string contains numbers
const numberPattern = /[0-9]/; 
let text = "Password!";

if (numberPattern.test(text) === false) {
    console.log("Must contain at least one number.");
}

Example 7: Standard Email Validation (Regex)

You don't need to memorize this formula, but you should know how to use it. It checks for string @ string . string.

javascript
123456789
// Example JavaScript
const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
let userEmail = "test@example.com";

if (emailPattern.test(userEmail)) {
    console.log("Valid Email format.");
} else {
    console.log("Invalid Email format.");
}

Example 8: Showing/Hiding Error Divs

Instead of using alerts, create error <p> tags in HTML, hide them with CSS (display: none), and show them with JS when validation fails.

javascript
1234567891011
// Example JavaScript
let errorMsg = document.getElementById("errorMsg");

function showError(message) {
    errorMsg.textContent = message;
    errorMsg.style.display = "block"; // Make it visible
}

function hideError() {
    errorMsg.style.display = "none";
}

Example 9: The classList approach for errors

Adding a CSS class that puts a red border around the invalid input field.

css
12
/* Example CSS */
.input-error { border: 2px solid red; background-color: #ffe6e6; }
javascript
12345678
// Example JavaScript
let myInput = document.getElementById("username");

if (myInput.value === "") {
    myInput.classList.add("input-error");
} else {
    myInput.classList.remove("input-error");
}

Example 10: The Master Validation Flag

When validating a form with many fields, use a boolean "flag" to track if *any* error occurred.

javascript
12345678910111213141516
// Example JavaScript
let isValid = true; // Assume form is good

if (name === "") {
    showError("Name missing");
    isValid = false; // Flag triggered
}

if (pass.length < 6) {
    showError("Pass too short");
    isValid = false; // Flag triggered
}

if (isValid) {
    console.log("Form is 100% perfect, send to server!");
}

---

5. Common Mistakes for Beginners

  1. 1. Forgetting value: Writing let username = document.getElementById("user"); gives you the HTML Element Object, not the text inside it! You must use .value.
  1. 2. Checking length of numbers: Numbers do not have a .length property. Number(100).length is undefined. You must check length on Strings.
  1. 3. Trusting Client-Side Validation: JavaScript validation is ONLY for User Experience. A malicious user can disable JS in their browser and bypass your checks. You MUST also validate data on your backend server (PHP/Node) before saving to a database.

6. Best Practices

  • Validate data in real-time (input or blur events) so users don't have to wait until they hit "Submit" to see their errors.
  • Never use alert() for validation errors. Build custom, inline HTML error messages right next to the fields that failed.

7. Mini Project: Signup Form Validator

Let's build a professional, multi-field signup form with custom error handling.

HTML:

html
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
<!-- Example HTML -->
<!DOCTYPE html>
<html>
<head>
    <style>
        /* Example CSS */
        body { font-family: Arial; background: #f4f4f9; display: flex; justify-content: center; padding-top: 50px; }
        .form-card { background: white; padding: 30px; border-radius: 8px; box-shadow: 0 4px 10px rgba(0,0,0,0.1); width: 350px; }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; color: #333;}
        input { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; transition: 0.3s;}
        input:focus { outline: none; border-color: #007bff; }
        button { width: 100%; padding: 12px; background: #007bff; color: white; border: none; border-radius: 4px; font-size: 16px; cursor: pointer; }
        
        /* Error States */
        .error-text { color: #dc3545; font-size: 12px; margin-top: 5px; display: none; }
        .input-error { border-color: #dc3545; background: #fff8f8; }
        
        #successMsg { display: none; background: #d4edda; color: #155724; padding: 10px; border-radius: 4px; margin-bottom: 15px; text-align: center;}
    </style>
</head>
<body>

    <div class="form-card">
        <div id="successMsg">Account Created Successfully!</div>
        <h2>Sign Up</h2>
        
        <form id="signupForm">
            <div class="form-group">
                <label>Username</label>
                <input type="text" id="username">
                <div class="error-text" id="nameError">Username is required.</div>
            </div>
            
            <div class="form-group">
                <label>Email</label>
                <input type="text" id="email">
                <div class="error-text" id="emailError">Please enter a valid email.</div>
            </div>
            
            <div class="form-group">
                <label>Password</label>
                <input type="password" id="password">
                <div class="error-text" id="passError">Password must be at least 6 characters.</div>
            </div>

            <button type="submit">Create Account</button>
        </form>
    </div>

    <script src="validate.js"></script>
</body>
</html>

validate.js:

javascript
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
// Example JavaScript
document.getElementById("signupForm").addEventListener("submit", function(event) {
    // 1. Prevent page refresh
    event.preventDefault();

    // 2. Get values and Elements
    let nameInput = document.getElementById("username");
    let emailInput = document.getElementById("email");
    let passInput = document.getElementById("password");
    
    // Reset all errors visually first
    document.querySelectorAll(".error-text").forEach(el => el.style.display = "none");
    document.querySelectorAll("input").forEach(el => el.classList.remove("input-error"));
    document.getElementById("successMsg").style.display = "none";

    let isValid = true; // Master flag

    // 3. Validate Username
    if (nameInput.value.trim() === "") {
        document.getElementById("nameError").style.display = "block";
        nameInput.classList.add("input-error");
        isValid = false;
    }

    // 4. Validate Email (Simple regex)
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(emailInput.value.trim())) {
        document.getElementById("emailError").style.display = "block";
        emailInput.classList.add("input-error");
        isValid = false;
    }

    // 5. Validate Password
    if (passInput.value.length < 6) {
        document.getElementById("passError").style.display = "block";
        passInput.classList.add("input-error");
        isValid = false;
    }

    // 6. Final Check
    if (isValid) {
        // If everything is perfect, show success
        document.getElementById("successMsg").style.display = "block";
        
        // In a real app, you would use Fetch API to send data to server here
        
        // Clear form
        this.reset(); // 'this' refers to the form
    }
});

8. Exercises

  1. 1. Write logic to check if an input field named zipcode contains exactly 5 characters.
  1. 2. Write logic to check if a checkbox (document.getElementById("terms").checked) is true. If not, show an error.
  1. 3. Why is trim() important when validating text fields?

9. MCQs (Multiple Choice Questions)

Q1: What property is used to get the text entered into an <input> field? A) .innerHTML B) .textContent C) .value D) .text *Answer: C*

Q2: What is the purpose of event.preventDefault() in form validation? A) To reset the form inputs. B) To stop the browser from refreshing the page. C) To prevent the user from typing. D) To securely encrypt the data. *Answer: B*

Q3: Which built-in function is used to test Regex patterns against a string? A) .check() B) .match() C) .test() D) .validate() *Answer: C*

10. Interview Questions

Q: If you have robust JavaScript form validation, do you still need backend validation? *A: Absolutely. Client-side (JS) validation is easily bypassed by tech-savvy users or automated bots disabling JavaScript. Backend validation is the only true security measure; JS validation is purely for improving the user experience by providing immediate feedback.*

11. FAQs

Q: HTML5 has required and minlength attributes. Why write JS validation at all? *A: HTML5 validation tooltips are hardcoded by the browser. You cannot easily change their style, their exact positioning, or translate their text dynamically. Custom JS validation gives you 100% control over the design and logic.*

12. Summary

  • Always use event.preventDefault() when handling forms.
  • Use .value to extract input data.
  • Check for empty strings (=== ""), lengths, and matching passwords.
  • Use Regex .test() for complex patterns like emails.
  • Display custom HTML errors by toggling CSS classes and display properties.

13. Next Chapter Recommendation

You have now mastered the fundamentals of classical JavaScript! In 2015, JavaScript received a massive update (ES6) that changed the language forever. In the next chapter, JavaScript ES6 Features, we will officially dive into modern syntax that professional developers use every day.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·