Table of contents
1.
Introduction
2.
JQuery Validation
3.
Jquery
4.
Using Plain jQuery
4.1.
Example: Validating a Simple Form
4.1.1.
HTML Code
4.1.2.
jQuery Code
5.
Validation in JQuery
5.1.
Examples
6.
Validation Using an Inbuilt jQuery Validation Plugin
6.1.
Steps to Use the Plugin
6.2.
Example: Validating a Registration Form
6.2.1.
HTML Code:
6.2.2.
jQuery Code:
7.
Key Differences Between Plain jQuery and jQuery Validation Plugin
8.
Frequently Asked Questions
8.1.
What is form validation in jQuery? 
8.2.
How is the jQuery Validation Plugin better than plain jQuery? 
8.3.
Can I customize error messages in jQuery validation? 
9.
Conclusion
Last Updated: Jan 8, 2025
Medium

JQuery Form Validation

Author Rahul Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

jQuery Form Validation is a widely used feature that helps developers ensure that users provide correct and complete input in forms before submission. By leveraging jQuery's simplicity and efficiency, form validation can be implemented quickly and effectively. This technique allows developers to enforce rules such as required fields, email format, or minimum length, ensuring data integrity and improving user experience.

JQuery Form Validation

In this article, you will learn about the basics of jQuery Form Validation, its syntax, commonly used methods, and how to create reliable form validations for your web applications.

JQuery Validation

JQuery validation is a process where we use jQuery to check if the data entered in a form meets specific requirements. It helps ensure that the data is correct & complete before it is sent to the server. This is important because it reduces errors & improves user experience. For example, if a user forgets to fill out a required field or enters an invalid email address, jQuery validation can alert them immediately.

JQuery makes this process simple by providing methods & plugins that handle most of the work for you. One of the most popular plugins for this purpose is the jQuery Validation Plugin. This plugin allows you to add validation rules to your form fields with minimal effort. You can define rules like "this field is required" or "this field must be an email address" & the plugin will take care of the rest.

Jquery

JQuery is a fast, small, & feature-rich JavaScript library. It simplifies tasks like HTML document traversal, event handling, & animation. One of the main reasons developers love jQuery is its ability to make JavaScript code shorter & easier to write. Instead of writing long lines of JavaScript, you can achieve the same results with just a few lines of jQuery.

For example, if you want to select an element with the ID "username" & change its text, you can do it like this in jQuery:

$("#username").text("Hello, User!");


In plain JavaScript, the same task would require more code:

document.getElementById("username").innerText = "Hello, User!";


JQuery also works across different browsers, so you don’t have to worry about compatibility issues. This makes it a great choice for beginners & experienced developers alike.

Using Plain jQuery

Plain jQuery provides flexible methods to validate forms. You can manually check user input for required fields, email formatting, or password length.

Example: Validating a Simple Form

Here is an example of a registration form with fields for name, email, and password. We'll validate these fields using plain jQuery.

HTML Code

<!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>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <form id="registrationForm">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name"><br><br>

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

        <label for="password">Password:</label>
        <input type="password" id="password" name="password"><br><br>

        <button type="submit">Submit</button>
    </form>
    <p id="errorMessages" style="color: red;"></p>

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

jQuery Code

$(document).ready(function () {
    $("#registrationForm").on("submit", function (event) {
        event.preventDefault(); // Prevent form submission

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

        // Validate name
        if (name === "") {
            errors += "Name is required.<br>";
        }

        // Validate email
        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailPattern.test(email)) {
            errors += "Please enter a valid email address.<br>";
        }

        // Validate password
        if (password.length < 6) {
            errors += "Password must be at least 6 characters long.<br>";
        }

        // Display errors or submit the form
        if (errors) {
            $("#errorMessages").html(errors);
        } else {
            $("#errorMessages").html("Form submitted successfully!");
            // Here you can proceed with form submission, e.g., via AJAX.
        }
    });
});


Explanation:

  1. The preventDefault() method prevents the form from submitting normally.
     
  2. Each input field is validated:
    • Name: Checks if the field is empty.
       
    • Email: Validates against a regex pattern.
       
    • Password: Ensures a minimum length of 6 characters.
       
  3. Error messages are displayed in a <p> element if validation fails.

Validation in JQuery

Validation in jQuery means checking the user input to ensure it meets specific criteria. This can include checking if a field is empty, if an email address is valid, or if a password meets certain requirements. jQuery provides several ways to perform validation, but the most common method is using the jQuery Validation Plugin.

To use this plugin, you first need to include jQuery & the validation plugin in your HTML file. This is how you can do it:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>


Once you’ve included these scripts, you can start adding validation rules to your form. For example, let’s say you have a form with a required email field. You can add validation like this:

<form id="myForm">
  <label for="email">Email:</label>
  <input type="text" id="email" name="email">
  <input type="submit">
</form>


<script>
  $(document).ready(function() {
    $("#myForm").validate({
      rules: {
        email: {
          required: true,
          email: true
        }
      },
      messages: {
        email: {
          required: "Please enter your email",
          email: "Please enter a valid email address"
        }
      }
    });
  });
</script>


In this example, the `validate` method is used to define validation rules for the email field. The `rules` object specifies that the email field is required & must contain a valid email address. The `messages` object defines custom error messages that will be displayed if the validation fails.

Examples

Let’s look at a more detailed example to understand how jQuery validation works in practice. Suppose you have a registration form with the following fields: name, email, password, & confirm password. You want to ensure that all fields are filled out, the email is valid, & the password matches the confirm password field.

Let’s see how you can implement this using jQuery validation:

<form id="registrationForm">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name"><br>

  <label for="email">Email:</label>
  <input type="text" id="email" name="email"><br>

  <label for="password">Password:</label>
  <input type="password" id="password" name="password"><br>

  <label for="confirmPassword">Confirm Password:</label>
  <input type="password" id="confirmPassword" name="confirmPassword"><br>


  <input type="submit">
</form>
<script>
  $(document).ready(function() {
    $("#registrationForm").validate({
      rules: {
        name: {
          required: true
        },
        email: {
          required: true,
          email: true
        },
        password: {
          required: true,
          minlength: 6
        },
        confirmPassword: {
          required: true,
          equalTo: "#password"
        }
      },
      messages: {
        name: {
          required: "Please enter your name"
        },
        email: {
          required: "Please enter your email",
          email: "Please enter a valid email address"
        },
        password: {
          required: "Please enter a password",
          minlength: "Password must be at least 6 characters long"
        },
        confirmPassword: {
          required: "Please confirm your password",
          equalTo: "Passwords do not match"
        }
      }
    });
  });
</script>


In this example, the `rules` object defines validation rules for each field. The `messages` object provides custom error messages for each rule. The `equalTo` rule ensures that the confirmed password field matches the password field.

Validation Using an Inbuilt jQuery Validation Plugin

The jQuery Validation Plugin is a powerful tool for form validation. It provides ready-to-use methods and simplifies the process significantly.

Steps to Use the Plugin

Include the plugin in your HTML file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js"></script>


Define validation rules for your form.

Example: Validating a Registration Form

HTML Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Validation Plugin</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js"></script>
</head>
<body>
    <form id="registrationFormPlugin">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name"><br><br>

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

        <label for="password">Password:</label>
        <input type="password" id="password" name="password"><br><br>

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

    <script src="script-plugin.js"></script>
</body>
</html>


jQuery Code:

$(document).ready(function () {
    $("#registrationFormPlugin").validate({
        rules: {
            name: "required",
            email: {
                required: true,
                email: true
            },
            password: {
                required: true,
                minlength: 6
            }
        },
        messages: {
            name: "Please enter your name",
            email: {
                required: "Please enter your email",
                email: "Enter a valid email address"
            },
            password: {
                required: "Please provide a password",
                minlength: "Your password must be at least 6 characters long"
            }
        },
        submitHandler: function (form) {
            alert("Form submitted successfully!");
            form.submit();
        }
    });
});


Explanation:

  1. The rules object specifies validation rules for each field.
    • required: Checks if the field is not empty.
       
    • email: Ensures valid email formatting.
       
    • minlength: Sets a minimum character length for the password.
       
  2. The messages object customizes error messages for each rule.
     
  3. The submitHandler function handles successful form submission.

Key Differences Between Plain jQuery and jQuery Validation Plugin

FeaturePlain jQueryjQuery Validation Plugin
FlexibilityHighMedium
Ease of UseModerateHigh
Built-in FeaturesFewMany
Code LengthLongerShorter

Frequently Asked Questions

What is form validation in jQuery? 

Form validation ensures that user input meets certain criteria before submission. Using jQuery simplifies this process by providing methods and plugins to validate input fields.

How is the jQuery Validation Plugin better than plain jQuery? 

The plugin offers pre-built rules, easy configuration, and shorter code, making it more efficient for complex validation tasks.

Can I customize error messages in jQuery validation? 

Yes, you can customize error messages for each validation rule using the messages object.

Conclusion

In this article, we discussed how to validate forms using plain jQuery and the jQuery Validation Plugin. By applying these techniques, you can enhance the user experience and ensure accurate data collection. Whether you're a beginner or an experienced developer, mastering form validation is a valuable skill for creating robust web applications.

You can also check out our other blogs on Code360.

Live masterclass