«Back to Home

Learn JavaScript

Topics

Working with Forms and Validation

Forms are one of the most important parts of any website. They are used for:

  • Login

  • Signup

  • Search

  • Contact forms

  • Checkout forms

  • Feedback and surveys

JavaScript helps you:

  • Read form input

  • Validate user data

  • Show error messages

  • Prevent form submission

  • Clean or reset forms

In this chapter, you will learn how to work with forms step-by-step.

1. Getting Form Input Values

HTML:

<input id="name" placeholder="Enter your name">
<button id="submitBtn">Submit</button>

JavaScript:

document.getElementById("submitBtn").addEventListener("click", () => {
    let username = document.getElementById("name").value;
    console.log("Name:", username);
});

Whenever the button is clicked, the input value is printed.

2. Basic Form Submission

HTML:

<form id="myForm">
    <input id="email" placeholder="Enter email">
    <button>Submit</button>
</form>

JavaScript:

document.getElementById("myForm").addEventListener("submit", (event) => {
    event.preventDefault();

    let email = document.getElementById("email").value;
    console.log("Email Submitted:", email);
});

3. Validating Empty Fields

document.getElementById("myForm").addEventListener("submit", (event) => {
    event.preventDefault();

    let email = document.getElementById("email").value;

    if (email === "") {
        console.log("Email is required");
        return;
    }

    console.log("Form submitted successfully");
});

4. Showing Error Messages on Page

HTML:

<input id="email" placeholder="Enter email">
<p id="error" style="color:red;"></p>
<button id="btn">Submit</button>

JavaScript:

document.getElementById("btn").addEventListener("click", () => {
    let email = document.getElementById("email").value;
    let errorBox = document.getElementById("error");

    if (email === "") {
        errorBox.textContent = "Email cannot be empty";
    } else {
        errorBox.textContent = "";
        console.log("Submitted:", email);
    }
});

5. Email Format Validation (Simple Check)

let email = "[email protected]";

if (email.includes("@") && email.includes(".")) {
    console.log("Valid email");
} else {
    console.log("Invalid email");
}

6. Password Validation Example

Basic rules:

  • At least 6 characters

  • Should not be empty

let pass = document.getElementById("password").value;

if (pass.length < 6) {
    console.log("Password must be at least 6 characters");
} else {
    console.log("Password OK");
}

7. Confirm Password Check

let pass1 = document.getElementById("pass1").value;
let pass2 = document.getElementById("pass2").value;

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

8. Real-Life Example: Signup Form Validation

HTML:

<form id="signup">
    <input id="user" placeholder="Username">
    <input id="email" placeholder="Email">
    <input id="pass" placeholder="Password" type="password">
    <button>Register</button>
</form>
<p id="msg"></p>

JavaScript:

document.getElementById("signup").addEventListener("submit", (event) => {
    event.preventDefault();

    let user = document.getElementById("user").value;
    let email = document.getElementById("email").value;
    let pass = document.getElementById("pass").value;
    let msg = document.getElementById("msg");

    if (user === "") {
        msg.textContent = "Username is required";
        return;
    }

    if (!email.includes("@")) {
        msg.textContent = "Invalid email";
        return;
    }

    if (pass.length < 6) {
        msg.textContent = "Password too short";
        return;
    }

    msg.textContent = "Registration Successful!";
});

9. Resetting the Form

document.getElementById("signup").reset();

This clears all fields.

10. Preventing Form Submission Until Valid

HTML:

<button id="btn" disabled>Submit</button>
<input id="input">

JavaScript:

let btn = document.getElementById("btn");
let inp = document.getElementById("input");

inp.addEventListener("input", () => {
    btn.disabled = inp.value === "";
});

Button becomes active only when the user types something.

Example Program (Complete)

document.getElementById("form").addEventListener("submit", (e) => {
    e.preventDefault();

    let name = document.getElementById("name").value;
    let age = document.getElementById("age").value;
    let msg = document.getElementById("message");

    if (name === "") {
        msg.textContent = "Name cannot be empty";
        return;
    }

    if (age < 18) {
        msg.textContent = "You must be at least 18";
        return;
    }

    msg.textContent = "Form Submitted Successfully!";
});

Common Mistakes Beginners Make

  • Forgetting to use event.preventDefault()

  • Validating after submission instead of before

  • Showing errors in console instead of on webpage

  • Not trimming whitespace (name.trim())

  • Using innerHTML for simple text updates instead of textContent