Paramclasses Academy - Blog

Tutorials Details

←
Post 10 of 15
→

What Is jQuery Form Validation?

What Is jQuery Form Validation?

October 14, 2026

What Is jQuery Form Validation? Rules, Error Messages and Examples


Introduction to jQuery Form Validation

Form validation is an important part of web development. It helps ensure that users enter the required information correctly before submitting a form.

For example, consider a registration form that asks users to enter their name, email address and password. What happens if a user leaves the name field empty or enters an invalid email address?

Form validation helps detect these problems and display appropriate error messages.

With jQuery, you can validate form fields, display error messages, check password requirements and prevent form submission when the input is invalid.

Common validation requirements include:

  • Checking whether a field is empty.

  • Validating email address format.

  • Checking minimum and maximum character lengths.

  • Verifying password requirements.

  • Comparing password and confirm-password fields.

  • Displaying error and success messages.

  • Preventing invalid form submission.

In this tutorial, you will learn how to implement these features with practical examples.

1. What Is Form Validation?

Form validation is the process of checking user-entered data against defined rules before accepting or processing it.

There are two main types of form validation.

Client-side validation

Client-side validation runs in the user's browser before the form data is submitted to the server.

Examples include checking required fields, validating an email format and comparing password fields.

Advantages:

  • Provides immediate feedback.

  • Reduces unnecessary requests to the server.

  • Improves the user experience.

  • Helps users correct mistakes quickly.

Server-side validation

Server-side validation runs on the server after the application receives the submitted data.

It is essential because users can bypass browser-based validation or send requests directly to the server.

For security, always validate important data on the server, even if you have already validated it using jQuery.

2. How to Include jQuery

To use jQuery form validation, first include the jQuery library in your HTML file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Form Validation</title>
</head>
<body>

    <form id="myForm">
        <input type="text" id="username" placeholder="Enter your name">
        <button type="submit">Submit</button>
    </form>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

    <script>
        $(document).ready(function () {

            $("#myForm").on("submit", function (event) {
                event.preventDefault();

                let username = $("#username").val().trim();

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

                alert("Form submitted successfully.");
            });

        });
    </script>

</body>
</html>

In this example, event.preventDefault() stops the browser's normal form submission so that jQuery can check the entered value first.

The example uses an alert for simplicity. In a professional form, inline error messages usually provide a better user experience.

3. Required Field Validation

Required field validation checks whether the user has entered a value into a required input.

Example

<form id="nameForm">
    <label for="name">Full Name</label>
    <input type="text" id="name">

    <p id="nameError"></p>

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

<script>
$("#nameForm").on("submit", function (event) {
    event.preventDefault();

    let name = $("#name").val().trim();

    if (name === "") {
        $("#nameError").text("Name is required.");
        return;
    }

    $("#nameError").text("");
    alert("Name validation successful.");
});
</script>

Explanation

  • .val() retrieves the input value.

  • .trim() removes spaces from the beginning and end.

  • The if condition checks whether the value is empty.

  • .text() displays the validation message.

Using .trim() also prevents a field containing only spaces from being accepted as a valid name.

4. Email Validation Using jQuery

An email field should contain an address in an acceptable format, such as student@example.com.

For a simple client-side check, you can use a regular expression.

Example

<input type="email" id="email" placeholder="Enter your email">
<p id="emailError"></p>

<script>
function isValidEmail(email) {
    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailPattern.test(email);
}

$("#email").on("input", function () {
    let email = $(this).val().trim();

    if (email === "") {
        $("#emailError").text("Email is required.");
    } else if (!isValidEmail(email)) {
        $("#emailError").text("Please enter a valid email address.");
    } else {
        $("#emailError").text("");
    }
});
</script>

How does this work?

The regular expression checks for a basic email structure:

  • Text before the @ symbol.

  • An @ symbol.

  • A domain name.

  • A dot followed by a domain suffix.

This is a practical format check, not proof that the email address exists. Server-side validation and, when necessary, email verification are still required.

5. Password Validation

Password validation checks whether the entered password meets the application's requirements.

For example, a registration form may require a password containing at least eight characters.

Example

<input type="password" id="password" placeholder="Enter password">
<p id="passwordError"></p>

<script>
$("#password").on("input", function () {
    let password = $(this).val();

    if (password.length < 8) {
        $("#passwordError").text(
            "Password must contain at least 8 characters."
        );
    } else {
        $("#passwordError").text("");
    }
});
</script>

You can extend the validation rules to require uppercase letters, lowercase letters, numbers or special characters if those requirements are appropriate for your application.

Avoid imposing unnecessarily complicated password rules. Clear password requirements and support for strong, unique passwords are generally more useful.

6. Confirm Password Validation

Registration forms often ask users to enter their password twice. The confirm-password field helps detect typing mistakes.

Example

<input type="password" id="password" placeholder="Enter password">
<input type="password" id="confirmPassword" placeholder="Confirm password">

<p id="confirmPasswordError"></p>

<script>
function validateConfirmPassword() {
    let password = $("#password").val();
    let confirmPassword = $("#confirmPassword").val();

    if (confirmPassword === "") {
        $("#confirmPasswordError").text(
            "Please confirm your password."
        );
    } else if (password !== confirmPassword) {
        $("#confirmPasswordError").text(
            "Passwords do not match."
        );
    } else {
        $("#confirmPasswordError").text("");
    }
}

$("#password, #confirmPassword").on(
    "input",
    validateConfirmPassword
);
</script>

The function runs whenever either password field changes, so the message updates as the user types.

7. Minimum and Maximum Length Validation

Sometimes, a field must contain a specific number of characters.

For example:

  • A username must contain at least three characters.

  • A username must not exceed twenty characters.

Example

let username = $("#username").val().trim();

if (username.length < 3) {
    $("#usernameError").text(
        "Username must contain at least 3 characters."
    );
} else if (username.length > 20) {
    $("#usernameError").text(
        "Username cannot exceed 20 characters."
    );
} else {
    $("#usernameError").text("");
}

You can apply similar rules to product names, comments, addresses and other text fields according to your application's requirements.

8. What Is the jQuery Validation Plugin?

The jQuery Validation Plugin is a separate library built to simplify form validation.

Instead of manually writing every validation condition, you can define rules and messages for each form field.

It supports common validation rules such as:

  • required

  • email

  • minlength

  • maxlength

  • equalTo

  • number

  • digits

The plugin is useful for forms with several fields and multiple validation rules.

Include the required libraries

Load jQuery first, followed by the validation plugin.

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.21.0/dist/jquery.validate.min.js"></script>

For production websites, review library versions and security updates before deployment.

Basic plugin example

<form id="registrationForm">
    <label for="fullName">Full Name</label>
    <input type="text" id="fullName" name="fullName">

    <label for="emailAddress">Email</label>
    <input type="email" id="emailAddress" name="emailAddress">

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

<script>
$(document).ready(function () {

    $("#registrationForm").validate({
        rules: {
            fullName: {
                required: true,
                minlength: 3
            },

            emailAddress: {
                required: true,
                email: true
            }
        },

        messages: {
            fullName: {
                required: "Please enter your full name.",
                minlength: "Name must contain at least 3 characters."
            },

            emailAddress: {
                required: "Please enter your email address.",
                email: "Please enter a valid email address."
            }
        },

        submitHandler: function (form) {
            alert("All validation rules passed.");
            // Replace this with your real submission process.
        }
    });

});
</script>

Important: This example demonstrates validation only. It does not send the form data to a server. A real registration system must submit the data to a backend endpoint that performs its own validation.

9. Complete Practical Project: Registration Form Validation

Let's build a responsive registration form with validation for:

  • Full name

  • Email address

  • Password

  • Confirm password

The example below uses the jQuery Validation Plugin to keep the validation rules organized.

Complete HTML, CSS and jQuery Code

Save the following code as jquery-form-validation.html.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>jQuery Registration Form Validation</title>

    <style>
        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            padding: 30px 15px;
            font-family: Arial, sans-serif;
            background: #eff6ff;
        }

        .container {
            width: 100%;
            max-width: 480px;
            margin: auto;
            padding: 28px;
            background: #ffffff;
            border-radius: 12px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
        }

        h1 {
            margin-top: 0;
            color: #1d4ed8;
            text-align: center;
        }

        .form-group {
            margin-bottom: 18px;
        }

        label {
            display: block;
            margin-bottom: 7px;
            font-weight: 600;
            color: #334155;
        }

        input {
            width: 100%;
            padding: 12px;
            border: 1px solid #cbd5e1;
            border-radius: 6px;
            font-size: 16px;
        }

        input:focus {
            outline: 2px solid #93c5fd;
            border-color: #2563eb;
        }

        input.error {
            border-color: #dc2626;
        }

        label.error {
            margin-top: 6px;
            color: #dc2626;
            font-size: 13px;
            font-weight: normal;
        }

        button {
            width: 100%;
            padding: 13px;
            border: none;
            border-radius: 6px;
            background: #2563eb;
            color: #ffffff;
            font-size: 16px;
            cursor: pointer;
        }

        button:hover {
            background: #1d4ed8;
        }

        #successMessage {
            color: #15803d;
            text-align: center;
        }

        @media (max-width: 480px) {
            .container {
                padding: 20px;
            }
        }
    </style>
</head>

<body>

<div class="container">

    <h1>Create Account</h1>

    <form id="registrationForm" novalidate>

        <div class="form-group">
            <label for="fullName">Full Name</label>
            <input
                type="text"
                id="fullName"
                name="fullName"
                autocomplete="name"
            >
        </div>

        <div class="form-group">
            <label for="email">Email Address</label>
            <input
                type="email"
                id="email"
                name="email"
                autocomplete="email"
            >
        </div>

        <div class="form-group">
            <label for="password">Password</label>
            <input
                type="password"
                id="password"
                name="password"
                autocomplete="new-password"
            >
        </div>

        <div class="form-group">
            <label for="confirmPassword">Confirm Password</label>
            <input
                type="password"
                id="confirmPassword"
                name="confirmPassword"
                autocomplete="new-password"
            >
        </div>

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

        <p id="successMessage" role="status" aria-live="polite"></p>

    </form>

</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.21.0/dist/jquery.validate.min.js"></script>

<script>
$(document).ready(function () {

    $("#registrationForm").validate({

        rules: {
            fullName: {
                required: true,
                minlength: 3,
                maxlength: 50
            },

            email: {
                required: true,
                email: true
            },

            password: {
                required: true,
                minlength: 8
            },

            confirmPassword: {
                required: true,
                equalTo: "#password"
            }
        },

        messages: {
            fullName: {
                required: "Please enter your full name.",
                minlength: "Name must contain at least 3 characters.",
                maxlength: "Name cannot exceed 50 characters."
            },

            email: {
                required: "Please enter your email address.",
                email: "Please enter a valid email address."
            },

            password: {
                required: "Please enter a password.",
                minlength: "Password must contain at least 8 characters."
            },

            confirmPassword: {
                required: "Please confirm your password.",
                equalTo: "Passwords do not match."
            }
        },

        errorElement: "label",
        errorClass: "error",

        errorPlacement: function (error, element) {
            error.insertAfter(element);
        },

        submitHandler: function (form) {

            $("#successMessage").text(
                "All validation rules passed successfully!"
            );

            // Demonstration only: no data is sent to a server.
            // Replace this with your actual submission process.
            return false;
        }

    });

});
</script>

</body>
</html>

How to test the project

  1. Open the HTML file in your browser.

  2. Submit the form without entering any information.

  3. Check the required-field messages.

  4. Enter an invalid email address.

  5. Enter a password shorter than eight characters.

  6. Enter a different confirm password.

  7. Correct all the fields and submit again.

When all rules pass, the form displays a success message. No account is actually created because the example does not connect to a backend.

10. Explanation of Important Code

The validate() method

$("#registrationForm").validate({
    rules: {
        fullName: {
            required: true,
            minlength: 3
        }
    }
});

The validate() method initializes the validation plugin for the selected form. The rules object defines the conditions each field must satisfy.

The required rule

email: {
    required: true
}

The email field must not be left empty.

The email rule

email: {
    email: true
}

The plugin checks whether the entered value has an acceptable email format.

The equalTo rule

confirmPassword: {
    equalTo: "#password"
}

The confirm-password field must match the password field.

The submitHandler callback

submitHandler: function (form) {
    alert("Validation passed.");
    return false;
}

The callback runs after the configured validation rules pass. In this tutorial, returning false keeps the example from submitting the form to a server.

For a real application, implement a proper submission process and repeat all necessary validation on the server.

11. Common Mistakes in jQuery Form Validation

Mistake 1: Forgetting the name attribute

The jQuery Validation Plugin uses the input's name attribute to associate validation rules with the field.

Incorrect:

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

Correct:

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

Mistake 2: Loading the validation plugin before jQuery

The validation plugin depends on jQuery.

Solution: Load the jQuery library first and the validation plugin second.

Mistake 3: Validating only in the browser

Client-side validation can be bypassed.

Solution: Always validate submitted data on the server.

Mistake 4: Forgetting to compare passwords

Checking only whether both fields are filled does not confirm that they match.

Solution: Use the equalTo rule or compare the values manually.

Mistake 5: Displaying errors without accessible labels

Users should be able to identify which field has an error.

Solution: Use clear labels, meaningful messages and appropriate accessibility attributes.

Mistake 6: Assuming a success message means data was saved

A client-side success message only indicates that the browser-side checks passed.

Solution: Display a true submission-success message only after the server confirms that the operation succeeded.

12. Best Practices for Form Validation

  • Use clear, specific error messages.

  • Validate required fields and expected formats.

  • Trim unnecessary whitespace from text inputs.

  • Keep validation rules consistent with server-side rules.

  • Never trust client-side validation for security.

  • Avoid displaying sensitive information in error messages.

  • Use HTTPS when transmitting sensitive form data.

  • Protect state-changing requests against CSRF where applicable.

  • Use accessible labels and ensure errors are easy to understand.

  • Test forms with empty, invalid, boundary-length and valid values.

13. Frequently Asked Questions (FAQs)

Q1. What is jQuery form validation?

jQuery form validation checks user-entered values against defined rules before allowing a form to proceed.

Q2. Why is form validation important?

It helps detect incomplete or incorrectly formatted data and guides users toward correcting their mistakes.

Q3. Can jQuery validate email addresses?

Yes. You can write a custom email-format check or use the email rule provided by the jQuery Validation Plugin.

Q4. What is the jQuery Validation Plugin?

It is a separate jQuery library that simplifies form validation through configurable rules and error messages.

Q5. How do you validate a required field?

You can check whether the field value is empty or configure the required: true rule in the validation plugin.

Q6. How do you compare password and confirm-password fields?

Use the equalTo rule in the plugin or compare both values with JavaScript.

Q7. Is client-side validation sufficient for security?

No. Users can bypass browser-based checks, so the server must validate the submitted data independently.

Q8. Can jQuery validation be used with PHP or CodeIgniter?

Yes. jQuery can validate fields in the browser, while PHP or CodeIgniter validates the submitted data on the server.

Q9. Does validation automatically save form data?

No. Validation checks whether the input meets the rules. A separate submission process is required to save data.

Q10. Can validation display custom error messages?

Yes. You can configure custom messages for each field and validation rule.

14. jQuery Form Validation Interview Questions

  1. What is form validation?

  2. What is the difference between client-side and server-side validation?

  3. How do you check whether a required field is empty?

  4. How can you validate an email address using jQuery?

  5. What is the jQuery Validation Plugin?

  6. What is the purpose of the required rule?

  7. What is the difference between minlength and maxlength?

  8. How do you confirm that two password fields match?

  9. What is the purpose of submitHandler?

  10. Why should server-side validation always be implemented?

  11. How can you display custom validation messages?

  12. How do you make form validation more accessible?

15. Practice Exercises

Try these exercises to improve your skills.

Exercise 1: Create a login form that validates the username and password fields.

Exercise 2: Create a registration form that validates the name, email and mobile number.

Exercise 3: Add a minimum length of eight characters to the password field.

Exercise 4: Validate a confirm-password field against the original password.

Exercise 5: Create a contact form with custom error messages for every required field.

Exercise 6: Connect a validated form to a PHP or CodeIgniter backend and display the server's response.

16. Multiple-Choice Questions (MCQs)

Q1. What is the main purpose of form validation?

A. To change the website background

B. To check user input against rules

C. To delete database records

D. To create CSS animations

Correct Answer: B. To check user input against rules

Q2. Which rule checks whether a field is mandatory in the jQuery Validation Plugin?

A. email

B. equalTo

C. required

D. maxlength

Correct Answer: C. required

Q3. Which rule checks whether an email has an acceptable format?

A. email

B. number

C. digits

D. equalTo

Correct Answer: A. email

Q4. Which rule compares a confirm-password field with another field?

A. required

B. equalTo

C. minlength

D. number

Correct Answer: B. equalTo

Q5. Is client-side validation enough to secure an application?

A. Yes, always

B. No, server-side validation is also required

C. Only for login forms

D. Only for email fields

Correct Answer: B. No, server-side validation is also required

Q6. What is the purpose of the submitHandler option?

A. To style the form

B. To run a callback after the configured validation rules pass

C. To automatically create a database

D. To load the jQuery library

Correct Answer: B. To run a callback after the configured validation rules pass

Conclusion

jQuery form validation helps developers build user-friendly forms by checking required fields, validating email formats, enforcing password rules and comparing confirm-password fields.

You have learned both manual validation using jQuery and plugin-based validation using the jQuery Validation Plugin. You also built a complete registration form with custom error messages and responsive styling.

For professional applications, combine clear client-side feedback with reliable server-side validation and security controls.

←
Post 10 of 15
→