Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

An Example of Using the jQuery Validation Plug-in

4.75/5 (36 votes)
23 Jun 2011CPOL7 min read 472.5K   17K  
This article presents an example to use jQuery validation plugin.

Introduction

This article presents an example of using the jQuery validation plug-in.

Background

The jQuery "Validation Plug-in" is an excellent tool for web pages to validate data entries at the client side using JavaScript. Unfortunately though, it is not easy to find a complete working example of how to use it. This article presents an example to use the jQuery Validation Plug-in. 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 of 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. This 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/2011
  • * Quick note #2: Some readers found out that the example does not work on IE at all. It is true after my own test on another computer (not sure why it worked on IE8 in 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/2011
  • * Quick note #3: Uploaded another copy of the example in the "jQueryValidationExample1.8.1.zip" file. It uses the "1.8.1" version of "jquery.validate.min.js". My tests show 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 pointed out the problems. - 6/20/2011

The Example Visual Studio Solution

The structure of the attached Visual Studio 2010 solution is as follows:

SolutionExplorer.jpg

The Validation Plug-in 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 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 Plug-in. 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 the jQuery Validation Plug-in 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 jQuery UI for this example. This function will be used as an Object Oriented class during validation. 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 fail validation.

I will first introduce the "Example.htm" page and then introduce the JavaScript class in "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 follows:

XML
<!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 a 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 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 with 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 Plug-in.
  • 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.

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

The jQuery Validation Plug-in 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 you want. In this example, if a text box fails validation, I will simply give it a red border.

Run the Example

Now that we have finished reviewing the code, we can test run the web page. Set the Example.htm file as the start up page; we can debug and run the application in 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 was successful.

Points of Interest

  • This article presented an example of using jQuery Validation Plug-in.
  • You may have noticed that I insert a div element into the DOM in the jquery.validate.wrapper.js file when I 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 jquery.validate.wrapper.js as it is in your applications, you should 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 use 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 revision: 6-18-2011.

License

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