CS Engineering Gyan

JavaScript Form Validation

Forms allow users to enter information into a website. For example, a registration form may collect a username, email address, password and mobile number. Before this information is processed, the application should check whether the entered values are complete and follow the required rules.

JavaScript Form Validation is the process of checking form data in the browser before it is submitted. JavaScript can detect missing values, incorrect formats and invalid combinations and can provide feedback to the user immediately.

Form validation is commonly used in registration forms, login pages, contact forms, admission applications, search forms, checkout pages and many other interactive websites.


What is Form Validation?

Form validation means checking whether the information entered into a form satisfies predefined requirements.

For example, a registration form may require a username, a properly formatted email address and a password with a minimum length. If one of these requirements is not satisfied, the form can display an appropriate error message instead of continuing with invalid data.

Example Validation Rules


Why is Form Validation Required?

Validation improves the quality of information submitted through a form. It also helps users identify mistakes before they continue to the next step.

Purpose How Validation Helps
Data Quality Helps prevent incomplete or incorrectly formatted input.
User Experience Provides feedback while the user is completing the form.
Error Detection Identifies common input mistakes before submission.
Application Logic Ensures that required values are available before processing.

Client-Side and Server-Side Validation

Form validation can be performed in the browser, on the server, or at both levels.

Validation Type Where It Runs Main Purpose
Client-Side Validation Web Browser Provides immediate feedback and catches common input errors.
Server-Side Validation Web Server Performs authoritative validation before accepting or processing data.

Client-side validation should not be treated as a security mechanism. A user can bypass browser-side JavaScript or send requests without using the page. Important data must therefore be validated again on the server.


Basic HTML Form

Before using JavaScript, we need an HTML form containing input elements.

<form id="registrationForm">

    <label>Name</label>
    <input type="text" id="name">

    <label>Email</label>
    <input type="email" id="email">

    <button type="submit">Submit</button>

</form>

The id attribute allows JavaScript to locate a particular input element.


Accessing Form Values with JavaScript

The value property is used to read the information entered into an input field.

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

console.log(name);

If the user enters Rahul, the variable name contains the value "Rahul".


Checking an Empty Field

One of the simplest validation rules is checking whether a required field contains a value.

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

if(name.trim() === "")
{
    alert("Name is required");
}

The trim() method removes unnecessary spaces from the beginning and end of a string. It is useful because an input containing only spaces should normally be treated as empty.


Using the submit Event

The submit event is triggered when the user submits a form. It is generally a better place for complete form validation than attaching validation only to a button click.

let form = document.getElementById("registrationForm");

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

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

The preventDefault() method stops the browser's default submission action. This gives JavaScript an opportunity to validate the data first.


Validating a Required Name

function validateName()
{
    let name = document.getElementById("name").value;

    if(name.trim() === "")
    {
        alert("Please enter your name");
        return false;
    }

    return true;
}

The function returns false when the validation fails and true when the value is acceptable.


Email Validation

HTML provides an email input type that performs basic browser-level checking. JavaScript can also be used when an application needs additional rules.

Basic Email Check

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

if(email.trim() === "")
{
    alert("Email is required");
}

Email Validation Using Regular Expression

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

let pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

if(pattern.test(email))
{
    console.log("Valid email");
}
else
{
    console.log("Invalid email");
}

The test() method checks whether the supplied string matches the regular expression and returns a Boolean value.

Regular expressions can be useful for basic format checking, but email validation should not attempt to reproduce every rule of the complete email specification.


Password Validation

Password validation checks whether a password satisfies the application's requirements.

Checking Password Length

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

if(password.length < 8)
{
    alert("Password must contain at least 8 characters");
}

Checking Password with Regular Expression

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

let pattern =
/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,}$/;

if(pattern.test(password))
{
    console.log("Password meets the required rules");
}
else
{
    console.log("Password does not meet the required rules");
}

The example requires at least eight characters, including an uppercase letter, a lowercase letter and a number. Password requirements should be chosen according to the application's security needs rather than using a single universal rule.


Confirm Password Validation

Registration forms often ask users to enter their password twice. JavaScript can compare both values.

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

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

if(password !== confirmPassword)
{
    alert("Passwords do not match");
}

The strict inequality operator !== is appropriate here because both values should contain exactly the same string.


Mobile Number Validation

A mobile number rule depends on the country and application. For an example that expects exactly ten digits, a regular expression can be used.

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

let pattern = /^[0-9]{10}$/;

if(pattern.test(mobile))
{
    console.log("Valid mobile number");
}
else
{
    console.log("Enter a 10-digit mobile number");
}

Number Validation

When a form expects a numeric value, JavaScript can check whether the supplied value can be interpreted as a number.

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

if(age.trim() === "" || Number.isNaN(Number(age)))
{
    alert("Please enter a valid number");
}

Converting the input with Number() makes the intended numeric check explicit.


Displaying Error Messages

Using alert boxes for every validation error can make a form difficult to use. A better approach is to display the message near the related input.

<input type="text" id="name">

<span id="nameError"></span>

JavaScript can then update the message:

let name = document.getElementById("name").value;
let error = document.getElementById("nameError");

if(name.trim() === "")
{
    error.textContent = "Name is required";
}
else
{
    error.textContent = "";
}

The textContent property is suitable for inserting plain validation messages without interpreting the message as HTML.


Highlighting Invalid Fields

A form can also provide visual feedback by adding a CSS class to an invalid input.

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

input.classList.add("invalid");

When the value becomes valid, the class can be removed.

input.classList.remove("invalid");

Using CSS classes is generally cleaner than repeatedly changing individual style properties from JavaScript.


Real-Time Validation

Sometimes validation is performed while the user is entering information. The input event is useful for this purpose.

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

password.addEventListener("input", function()
{
    console.log(password.value.length);
});

Real-time validation can be useful for password requirements, character limits and other feedback where the user benefits from immediate information.


Common Form Events

Event Purpose
submit Occurs when the form is submitted.
input Occurs when the value of an input changes as the user enters data.
change Occurs when an element's value changes and the change is committed.
focus Occurs when an element receives focus.
blur Occurs when an element loses focus.

HTML5 Validation Attributes

JavaScript is not the only way to validate forms. Modern HTML provides several built-in validation features.

Attribute Purpose
required Requires the user to provide a value.
minlength Specifies the minimum number of characters.
maxlength Specifies the maximum number of characters.
min Specifies the minimum numeric value.
max Specifies the maximum numeric value.
pattern Defines a regular-expression pattern for supported input types.

Example

<input
    type="text"
    id="username"
    required
    minlength="5"
    maxlength="20"
>

The browser can automatically check these constraints before allowing a normal form submission to continue.


Using checkValidity()

JavaScript can also use the browser's built-in constraint validation system.

let form = document.getElementById("registrationForm");

if(form.checkValidity())
{
    console.log("Form is valid");
}
else
{
    console.log("Form contains invalid data");
}

The checkValidity() method returns true when the form satisfies its validation constraints and false otherwise.


Complete Registration Form Validation

The following example combines several concepts into one practical registration form. It validates the username, email, password and confirmation password before allowing the submission to continue.

<form id="registrationForm">

    <label>Username</label>
    <input type="text" id="username" required>

    <label>Email</label>
    <input type="email" id="email" required>

    <label>Password</label>
    <input type="password" id="password" required>

    <label>Confirm Password</label>
    <input type="password" id="confirmPassword" required>

    <button type="submit">Register</button>

</form>

<script>

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

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

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

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

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

    const confirmPassword =
    document.getElementById("confirmPassword").value;

    const emailPattern =
    /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

    if(username === "")
    {
        alert("Please enter username");
        event.preventDefault();
        return;
    }

    if(!emailPattern.test(email))
    {
        alert("Please enter a valid email address");
        event.preventDefault();
        return;
    }

    if(password.length < 8)
    {
        alert("Password must contain at least 8 characters");
        event.preventDefault();
        return;
    }

    if(password !== confirmPassword)
    {
        alert("Passwords do not match");
        event.preventDefault();
        return;
    }

    alert("Form validation successful");

});

</script>

In a real application, successful client-side validation would normally be followed by sending the form data to a server for further validation and processing.


Form Reset

The reset() method can be used to restore a form to its initial state.

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

This can be useful when a user wants to clear the form or when an application needs to reset the interface after a particular action.


Preventing Invalid Form Submission

The preventDefault() method is commonly used when custom JavaScript validation is performed during the submit event.

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

    if(validationFailed)
    {
        event.preventDefault();
    }

});

If validation succeeds, the application can allow the normal submission process or send the data using an appropriate API request.


Advantages of Client-Side Validation


Limitations of Client-Side Validation

For applications that accept important or sensitive information, the server should independently validate the received data before storing or processing it.


Common Mistakes in JavaScript Form Validation

Mistake Better Approach
Checking only whether a field is empty Validate the format and business rules required by the application.
Using only client-side validation Perform server-side validation as well.
Showing generic error messages Explain which field needs correction.
Repeating the same validation code Create reusable validation functions where appropriate.
Ignoring whitespace Use methods such as trim() where appropriate.
Using complicated regular expressions unnecessarily Use patterns that match the actual requirement of the application.

Best Practices for JavaScript Form Validation


Real-World Uses of Form Validation

Form validation is useful anywhere a website accepts structured information from users.


Frequently Asked Questions

1. What is JavaScript Form Validation?

JavaScript Form Validation is the process of checking user-entered form data in the browser before it is submitted or processed.

2. What is the purpose of preventDefault()?

The preventDefault() method stops the browser's default action for an event. During form validation, it can prevent submission when the entered data is invalid.

3. Can JavaScript validation replace server-side validation?

No. Client-side validation can be bypassed, so important data must also be validated on the server.

4. How can JavaScript read an input value?

JavaScript can access an input element and read its value property.

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

5. What is a regular expression?

A regular expression is a pattern used to search for or validate text according to defined rules.

6. How can two passwords be compared?

Read both input values and compare them using the strict inequality or equality operators.

if(password !== confirmPassword)
{
    // Passwords are different
}

7. What is checkValidity()?

The checkValidity() method checks whether an element or form satisfies its built-in HTML validation constraints.


JavaScript Form Validation Interview Questions

  1. What is form validation in JavaScript?
  2. Why is client-side validation useful?
  3. What is the difference between client-side and server-side validation?
  4. How can JavaScript access the value of an input element?
  5. What is the purpose of preventDefault()?
  6. How can you validate an email address?
  7. What is a regular expression?
  8. How can you check password length?
  9. How can two password fields be compared?
  10. What is the difference between required and JavaScript validation?
  11. What is the purpose of the submit event?
  12. What is checkValidity()?
  13. How can validation errors be displayed beside an input field?
  14. Why should server-side validation still be performed?
  15. What are the common HTML5 validation attributes?

Summary

JavaScript Form Validation helps developers check user input before it is processed. Common validation tasks include checking required fields, validating email formats, checking password requirements, comparing passwords, validating numbers and displaying useful error messages.

JavaScript can work together with HTML5 validation features such as required, minlength, maxlength, min, max and pattern. Events such as submit and input can be used to control when validation takes place.

Client-side validation improves the user experience, but it is not a replacement for server-side validation. A reliable web application should validate important data on the server before accepting, storing or processing it.


← Previous: DOM Manipulation Next: JavaScript Timers →
Home Visit Our YouTube Channel