8 min read

Form validation is a critical procedure in data collection. A correct validation in place makes sure that forms collect correct and expected data. Validation must be done on server side and optionally on client side. Server-side validation is robust and secure because a user will not access to modify its behaviour. However, client-side validation can be tempered easily. Applications relying on client-side validation completely and bypassing at server side are more open to security threats with data exploits.

Client-side validation is about giving users a better experience. This is so that users don’t have to go through everything on the page or submit a whole form to find out that they have one or even a few entries incorrect, but rather alerting users instantly to correct mistakes in place. Modern browsers enforce client-side validation by default for form fields in an HTML5 document with certain attributes (that is, required). There are cross-browser limitations on how these validation messages can be styled, positioned, and labeled.

JavaScript plays a vital role in client-side form validation. There are many different ways to validate a form using JavaScript. JavaScript libraries such as jQuery also provide a number of ways to validate a form. If a project is using any such library already, it would easier to utilize the library’s form validation methods.

jQuery validation is a jQuery plugin that makes it convenient to validate a HTML form. We will take a quick look at it below.

Installation

There are a number of following ways to install this library.

For simplicity of this tutorial’s demo we will use CDN hosted files.

Usage

Now that we have installed jQuery Validation we start by adding it to our HTML document. Here is the HTML for our demo app:

<!DOCTYPE html>
<html>
<head>
    <title>Learn jQuery Validation</title>
</head>
<body>
    <div class="container">
        <h1>Learn jQuery Validation</h1>
        <form method="post">
            <div>
                <label for="first-name">First Name:</label>
                <input type="text" id="first-name" name="first_name">
            </div>
            <div>
                <label for="last-name">Last Name:</label>
                <input type="text" id="last-name" name="last_name">
            </div>
            <div>
                <label for="email-address">Email:</label>
                <input type="text" id="email-address" name="email_address">
            </div>
            <div>
                <button type="submit" id="submit-cta">Submit</button>
            </div>
        </form>
    </div>

    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.min.js)></script>
</body>
</html>

All jQuery validation plugin methods are instantly available after the page is loaded. In the following example we add required attribute to our form fields, which will be used by the jQuery Validation plugin for basic validation:

...
<form method="post">
    <div>
        <label for="first-name">First Name:</label>
        <input type="text" id="first-name" name="first_name" required>
    </div>
    <div>
        <label for="last-name">Last Name:</label>
        <input type="text" id="last-name" name="last_name" required>
    </div>
    <div>
        <label for="email-address">Email:</label>
        <input type="text" id="email-address" name="email_address" required>
    </div>
    <div>
        <button type="submit" id="submit-cta">Submit</button>
    </div>
</form>
...

This simply enables HTML5 browser validation in most modern browsers. Adding the following JavaScript line will activate the jQuery Validation plugin.

$('form').validate();

validate() is a special method exposed by the jQuery Validation plugin and it can help customise our validation further. We will discuss this method in more details later in this article. Here is it in action:

See the Pen jQuery Validation – Part I by Jabran Rafique (@jabranr) on CodePen.

Submitting the form will validate the form and for empty fields it will return an error message. The generic error messages (This field is required) you see are set as default messages by the plugin. These can easily be changed by adding a data-msg-required attribute to the form field element, as shown in the following example:

...
<form method="post">
    <div>
        <label for="first-name">First Name:</label>
        <input type="text" id="first-name" name="first_name" required data-msg-required="First name is required.">
    </div>
    <div>
        <label for="last-name">Last Name:</label>
        <input type="text" id="last-name" name="last_name" required data-msg-required="Last name is required.">
    </div>
    <div>
        <label for="email-address">Email:</label>
        <input type="text" id="email-address" name="email_address" required data-msg-required="Email is required.">
    </div>
    <div>
        <button type="submit" id="submit-cta">Submit</button>
    </div>
</form>
...

Here it is in action:

See the Pen jQuery Validation – Part II by Jabran Rafique (@jabranr) on CodePen.

Similarly we can add different types of validation to our form fields using attributes such as minlength, maxlength, and so on, as shown in the following examples:

...
<div>
    <label for="phone">Phone:</label>

    <!-- With default error messages -->
    <input type="text" id="phone" name="phone" minlength="11" maxlength="15">

    <!-- With custom error messages -->
    <input type="text" id="phone" name="phone" minlength="11" maxlength="15" data-msg-min="Enter minimum of 11 digits." data-msg-max="Enter maximum of 15 digits.">
</div>
...

The alternative way of setting rules and messages is to pass these settings as arguments to the validate() method. Here are the above examples using the validate() method.

Here is the HTML for the form with no custom validation messages and optionally no validation attributes:

...
<form method="post">
    <div>
        <label for="first-name">First Name:</label>
        <input type="text" id="first-name" name="first_name">
    </div>
    <div>
        <label for="last-name">Last Name:</label>
        <input type="text" id="last-name" name="last_name">
    </div>
    <div>
        <label for="email-address">Email:</label>
        <input type="text" id="email-address" name="email_address">
    </div>
    <div>
        <button type="submit" id="submit-cta">Submit</button>
    </div>
</form>
...

Here is the JavaScript that enables validation and set custom validation messages for this form:

$('form').validate({
    rules: {
        'first_name': required,
        'last_name': required,
        'email_address': {
            required: true,
            email: true
        }
    },
    messages: {
        'first_name': 'First name is required.',
        'last_name': 'Last name is required.',
        'email_address': {
            required: 'Email is required.',
            email: 'A valid email is required.'
        }
    }
});

As you may have noticed a new validation constraint in the above code that is email: true. This enables checks for a valid email address. There are many more built-in constraints in the jQuery validation plugin. You can find those in the official documentation.

validate() has other properties that can be updated to customised the behavior of the jQuery Validation plugin completely. Some of those are the following:

  • errorClass: Set custom CSS class for error message element
  • validClass: Set custom CSS class for a validated element
  • errorPlacement(): Define where to put error messages
  • highlight(): Define method to highlight error/validated states
  • unhighlight(): Define method to unhighlight error/validated states

The default plugin methods can also be overidden for custom implementations using Validator object.

Additional Methods

Sooner or later in every other project, there arises a requirement for some advanced validation. Let’s think of date of birth fields. We want to validate all three fields as one and it is not possible to do so using the default methods of this plugin. There are optional additional methods to include if such a requirement appears. The additional methods can either be a script included using CDN link or each of them can be included individually when using bower installation.

Contribute

Contributions to any open source project make it robust and more useful with bugfixes and new features. Just like any other open source project, the jQuery Validation plugin also welcomes contributions. To contribute to the jQuery Validation plugin project just head over to the GitHub project and fork the repository to work on an existing issue or by adding or start a new one. Don’t forget to read the contribution guidelines before starting.

All of the demos in this tutorial can be found at CodePen as Collection. Hope this quick get started guide will make it easier to use the jQuery Validation plugin in your next project for better form validation.

Author

Jabran Rafique is a London-based web engineer. He currently works as a front-end web developer at Rated People. He has a master’s in computer science from Staffordshire University and more than 6 years of professional experience in web systems. He has also served as aregional lead and advocate at Google Map Makersince 2008, where he contributed to building digital maps in order to make them available to millions of people worldwide as well as organize and speak at international events. He writes on his website/blog about different things, and shares code at GitHub and thoughts on Twitter.

LEAVE A REPLY

Please enter your comment!
Please enter your name here