Click here to Skip to main content
15,893,722 members
Articles / Programming Languages / Javascript

An Example to Use jQuery Validation Plugin

Rate me:
Please Sign up or sign in to vote.
4.75/5 (36 votes)
20 Jun 2011CPOL7 min read 465.2K   17K   75  
This article presents an example to use jQuery validation plugin.
This is an old version of the currently published article.

Download jQueryValidationExample.zip - 135.06 KB
Download jQueryValidationExample1.8.1.zip - 134.92 KB

Introduction

This article presents an example to use jQuery validation plugin. 

Background

The "jQuery" "Validation Plugin" is an excellent tool for web pages to validate the data entries at the client side using javascript. Unfortunately though, it is not easy to find a complete working example on how to use it. This article is to present an example to use "jQuery Validation Plugin". I have tested the example in IE8, Google Chrome, Firefox, and Safari. This example does not run well in IE7 and below. This small article assumes that you have some basic knowledge in "jQuery" and how to use it. If you are new to "jQuery", you can easily find a lot of information on how to use it over the internet.

* Quick note #1: The attached example does not work well in IE7. It is because the "jquery.validate.min.js" that I used in this example is version "1.5.5". After I finished the article, I found that if you use a newer version "1.8.1", it should work in IE7. You can download the version "1.8.1" from here. - 6/19/2010

* Quick note #2: Some readers found out that the example does not work on IE all. It is true after my own test on another computer (not sure why it worked on IE8 at my first test). But if you replace the "1.5.5" version "jquery.validate.min.js" with the version "1.8.1", my test shows that the example also works in IE. I will re-upload a copy using "1.8.1". Thanks for the feedback. - 6/20/2010

* Quick note #3: Uploaded another copy of the example in the "jQueryValidationExample1.8.1.zip" file. It uses the "1.8.1" version of the "jquery.validate.min.js". My test shows that it works on IE7+, Chrome, Safari, and Firefox. If you are interested, you can download both versions and see the difference. Thanks to the readers who point out the problems. - 6/20/2010

The Example Visual Studio Solution 

The structure of the attached visual studio 2010 solution is the following:

SolutionExplorer.jpg 

The "Validation Plugin" relies on "jQuery" and "jQuery UI" to work, so I included the "jquery-1.6.1.min.js" file from "jQuery" and the "jquery-ui-1.8.13.custom.min.js" file from "jQuery UI" in the "Scripts" folder. The "ui-lightness" folder and its contents in the "Styles" folder are the "Style Sheet" and the image resources used by the "jQuery UI". They come with the same download package when you download the "jquery-ui-1.8.13.custom.min.js" file. The "jquery.validate.min.js" file is the "jQuery Validation Plugin". The version used in this example is "1.5.5". 

The code that I wrote for this example is in the following files: 

  • The "Example.htm" file is the example html page to use "jQuery Validation Plugin" through the javascript class created in the "jquery.validate.wrapper.js" file. 
  • The "jquery.validate.wrapper.js" file implements a simple javascript function that wraps the "jQuery UI" for this example. This function will be used as an "Object Oriented" class during the validation. The "Object Orientation" is not fully supported in javascript, but we can somehow simulate it to a certain degree. If you are interested, you can take a look at this link.
  • The "Site.css" file has a simple "CSS" class that is used to highlight the input controls that fails the validation.

I will first introduce the "Example.htm" page and then introduce the javascript class in the "jquery.validate.wrapper.js". At last I will introduce the "CSS" class in the "Site.css" file.

The "Example.htm" File  

The "Example.htm" file is implemented as the following: 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Validation Example</title>
    <link href="Styles/ui-lightness/jquery-ui-1.8.13.custom.css"
        rel="stylesheet" type="text/css" />
    <link href="Styles/Site.css" rel="stylesheet" type="text/css" />
 
    <script src="Scripts/jquery-1.6.1.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery-ui-1.8.13.custom.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.validate.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.validate.wrapper.js" type="text/javascript"></script>
 
<script type="text/javascript" language="javascript">
 
    $(document).ready(function () {
        // 1. prepare the validation rules and messages.
        var rules = {
            textbox1: {
                required: true,
                minlength: 2
            },
            textbox2: "required",
            textbox3: "required"
        };
        var messages = {
            textbox1: {
                required: "textbox1 is required",
                minlength: "textbox1 needs to be at least length 2"
            },
            textbox2: "textbox2 is requried",
            textbox3: "textbox3 is required"
        };
 
        // 2. Initiate the validator
        var validator
            = new jQueryValidatorWrapper("FormToValidate",
                rules, messages);
 
        // 3. Set the click event to do the validation
        $("#btnValidate").click(function () {
            if (!validator.validate())
                return;
 
            alert("Validation Success!");
        });
    });
       
</script>
</head>
 
<body>
 
<form id="FormToValidate" action="#">
<table>
    <tr>
        <td>
            <input type="text" id="textbox1" name="textbox1" />
        </td>
        <td>
            <input type="text" id="textbox2" name="textbox2" />
        </td>
    </tr>
    <tr>
        <td>
            <input type="text" id="textbox3" name="textbox3" />
        </td>
        <td>
            <input type="button" id="btnValidate"
                style="width: 100%" value="Validate" />
        </td>
    </tr>
</table>
</form>
 
</body>
</html>

This html file has three text boxes and one button. The purpose of this example is to validate the content in the text boxes when the button is clicked. To set up the validation, we need to go through three steps in the "$(document).ready" event.

  • Prepare the validation rules and the messages to show if the validation fails.
  • Create a validator object by passing the "id" of the "Html Form" that contains the text boxes to the "jQueryValidatorWrapper" function. The validation rules and messages are also passed to this function. The "jQueryValidatorWrapper" function is implemented in the "jquery.validate.wrapper.js" file.
  • Hook up the click event for the button to start the validation.

This piece of code is pretty simple, but you should pay some attention to the following:

  • All the required javascript files and style sheets need to be referenced properly.
  • All the text boxes need to have a "name" attribute. The validation rules and messages are associated to the "name" attribute.
  • All the text boxes to be validated need to be in the "Html Form" that is used to create the validator object.

Now let us take a look at the "jQueryValidatorWrapper" function.

The jQuery Validation Wrapper

The "jQueryValidatorWrapper" function is implemented in the "jquery.validate.wrapper.js" file:

JavaScript
var dialogIdSeed = 1000000000;
function jQueryValidatorWrapper(formId, rules, messages) {
    // Get an Id for the "<div>" to diaply the error messages.
    // The Id is made sure to be unique in the web page.
    var dialogId = "V_dia_log" + dialogIdSeed++;
    while ($("#" + dialogId).length != 0) {
        alert(dialogId);
        dialogId = "V_dia_log" + dialogIdSeed++;
    }
 
    // create the error message "div" and add it to the dom.
    // it will be use to display the validation error messages.
    var dialogText = "<div id='" + dialogId
            + "' title='Please correct the errors ...'>"
            + "<ul /></div>";
    $("body").append(dialogText);
    var $dialog = $("#" + dialogId);
    var $ul = $("#" + dialogId + ">ul");
 
    $dialog.dialog({
        autoOpen: false,
        modal: true,
        close: function (event, ui) {
            $ul.html("");
        }
    });
 
    // hook up the form, the validation rules, and messages with jQuery validate.
    var showErrorMessage = false;
    var validator = $("#" + formId).validate({
        onchange: true,
        rules: rules,
        messages: messages,
        errorPlacement: function (error, element) {
            if (showErrorMessage) {
                var li = document.createElement("li")
                li.appendChild(document
                    .createTextNode(error.html()));
                $ul.append(li);
            }
        },
        showErrors: function (errorMap, errorList) {
            this.defaultShowErrors();
            if ((errorList.length != 0) && showErrorMessage) {
                $dialog.dialog('open');
            }
        }
    });
 
    // This is the function to call whem make the validation
    this.validate = function () {
        showErrorMessage = true;
        var result = validator.form();
        showErrorMessage = false;
 
        return result;
    };
}

The "jQueryValidatorWrapper" function does the following:

  • It first creates a "div" element and appends it to the "DOM". It makes sure that the "id" of the "div" element is unique in the web page. This "div" element will be used as a dialog box to display the error messages if the validation fails.
  • It hooks up the validation rules and messages with the "Html Form" that will be validated using the "jQuery Validation Plugin".
  • At last, it creates a function that starts the validation.

The "CSS" to Highlight the Failed Input Element

If the validation fails a textbox, we need to highlight it. The "CSS" class used to highlight the html element is implemented in the "Site.css" file.

HTML
.error
{
 border-color:red;
 border-style:solid;
 border-width:1px;
}

The "jQuery Validation Plugin" will look for the ".error" class to apply styles to failed html elements. You can implement this "CSS" class to highlight the failed elements whatever way that you want. In this example, if a text box fails the validation, I will simply give it a red border.

Run the Example

Now we finish reviewing the code, we can test run the web page. Set the "Example.htm" file as the start up page, we can debug run the application in the visual studio.

RunAppStart.jpg

When the web page first loads, we can see the three text boxes and the "validate" button.

RunAppFailAll.jpg

Without typing anything in the text boxes and clicking the "validate" button, the validation will fail all the three text boxes. The text boxes are highlighted with red borders and a dialog box shows up asking us to correct the problems.

RunAppElementValidate.jpg

After closing the dialog box, we can type something into the text boxes. You may notice that when the text in a text box becomes valid, the red border disappears.

RunAppSuccess.jpg

If we give all the three text boxes valid texts, clicking the "validate button" shows up the message box telling us that the validation is successful.

Points of Interest 

  •  This article presented an example to use jQuery validation plugin.
  • You may notice that I will insert a "div" element into the "DOM" in the "jquery.validate.wrapper.js" file when you initiate the validator. This "div" element will be given an "id" in the form of "V_dia_log1???..". If you accidentally have an html element having an "id" of the same pattern in your web page, the "jQueryValidatorWrapper" function will eventually find a unique "id" for the "div" element, but it may take some time. If you want to use the "jquery.validate.wrapper.js" as it is in your applications, you do better avoid assigning any element in the page an "id" of the same pattern. 
  • I have tested the example in IE8, Google Chrome, Firefox, and Safari. This example does not run well in IE7 and below. My test is limited though. If you find anything interesting in your own test, please do not hesitate to let me know and I will appreciate it.
  • The attached example does not work well in IE7. It is because the "jquery.validate.min.js" that I used in this example is version "1.5.5". After I finished the article, I found that if you use a newer version "1.8.1", it should work in IE7. You can download the version "1.8.1" from here.
  • I hope you like my postings and I hope this article can help you one way or the other.

History

First revisoin: 6-18-2010.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
I have been working in the IT industry for some time. It is still exciting and I am still learning. I am a happy and honest person, and I want to be your friend.

Comments and Discussions

Discussions on this specific version of this article. Add your comments on how to improve this article here. These comments will not be visible on the final published version of this article.