Tuesday, March 5, 2013
0 comments

Using jQuery Validation in ASP.NET Master Pages

4:24 PM
jQuery also has a Validation plug-in which is full of features and is quite flexible. However the name mangling in ASP.NET Master Pages presents interesting challenges in using this plug-in with it and I could not find a working solution on the net. In this article, I will demonstrate how to use the jQuery Validation plug-in with Master Pages. This article does not compare jQuery validation with ASP.NET Validation Controls, but has been written with the intention of demonstrating how jQuery Validation can be used in ASP.NET.
Note: ASP.NET Validation controls runs on client as well as server side, and you should ‘always’ perform validation on server-side.
I assume you are familiar with jQuery. If you are new to jQuery, then before moving ahead, I would recommend you to check out Using jQuery with ASP.NET - A Beginner's Guide. Please do take a note that this example uses jQuery’s current version - jQuery 1.3.2 and jQuery 1.3.2 Visual Studio 2008 Autocomplete documentation.
jQuery Validation Plug-in
bassisstance.de has provided a cool jQuery Validation Plugin that has the following features(only a few listed here):
-      Standard validation methods for validating fields like emails, digits, date, URLs, credit card numbers and much more.
-      Hide and display error messages as needed
-      Validation on Keyup, Blur, Submit button
-      Flexibility in specifying validation rules
The plug-in runs client-side and suits most of the validation requirement; however there are challenges while implementing it with an ASP.NET application. The challenge gets stronger when we deal with ASP.NET Master Pages. We will see how.
When you are using a MasterPage, the ASP.NET runtime modifies a WebControl’s ClientID, with each level of container prefixing its ID to the control, to ensure uniqueness. So for example, a TextBox called ‘txtName’ gets rendered as ‘ctl00$ContentPlaceHolder1$txtName’ (assuming the container is ContentPlaceHolder1) as shown below:
<input name="ctl00$ContentPlaceHolder1$txtName" type="text id="ctl00_ContentPlaceHolder1_txtName" />
Now the jQuery Validation plug-in relies on elements having a ‘name’ attribute. So referencing a control using $('#<%= txtName.ClientID%>') doesn’t really work with jQuery Validation plug-in. Instead what is needed is to use the controls ‘name’ attribute with the jQuery Validation control. With the name mangling in ASP.NET Master Pages, here’s how to solve the problem
Step 1: Create an ASP.NET website with a Master Page and a Content Page.
Step 2: Download jQuery 1.3.2, jQuery VS 2008 Doc and jQuery Validation plug-in. Create a ‘Scripts’ folder in the Solution Explorer of your project and add these files to this folder.
Assuming you have downloaded these files, create a reference to these files in the <head> section of your Master page as shown below:
<head runat="server">
    <title>jQuery Validation in ASP.NET Master Page</title>
    <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
    <script src="Scripts/jquery.validate.js" type="text/javascript"></script>
 
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
Step 3: Now go to your ContentPage and add two Textboxes and a Button inside the ContentPlaceHolder as shown below:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    Name: <asp:TextBox ID="txtName" MaxLength="30" runat="server" /><br />
    Email: <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox><br />
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</asp:Content>
Step 4: Now inside this ContentPage, add the following script to enable jQuery Validation
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <script type="text/javascript">
        $(document).ready(function() {
            $("#aspnetForm").validate({
                rules: {
                    <%=txtName.UniqueID %>: {
                        minlength: 2,
                        required: true
                    },
                     <%=txtEmail.UniqueID %>: {                       
                        required: true,
                        email:true
                    }
                }, messages: {}
            });
        });
    </script>
   
    Name: <asp:TextBox ID="txtName" MaxLength="30" runat="server" /><br />
    Email: <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox><br />
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</asp:Content>
Since the jQuery Validation plug-in relies on elements having a ‘name’ attribute, observe how we are using the UniqueID of the controls to reference them like <%=txtName.UniqueID %> and apply validation rules to them.
Run the application and click on the Submit button. The Validation fires displaying the error messages as shown below
jQuery Validation In Master Pages
On entering invalid data, the following message appears
jQuery Validation
If you want to display custom messages, make use of the ‘messages’ parameter to specify a custom error message for a field as shown below:
    <script type="text/javascript">
        $(document).ready(function() {
            $("#aspnetForm").validate({
                rules: {
                    <%=txtName.UniqueID %>: {
                        minlength: 2,
                        required: true
                    },
                     <%=txtEmail.UniqueID %>: {                       
                        required: true,
                        email:true
                    }
                }, messages: {
                    <%=txtName.UniqueID %>:{
                        required: "* Required Field *",
                        minlength: "* Please enter atleast 2 characters *"
                    }
               }
            });
        });
    </script>
So as seen in the screenshot below, using the ‘messages’ parameter, the error message ‘This field is required’ gets replaced with ‘* Required Field’ . You can also add some css to the error message as per your requirement.
Custom Error Message
That’s it for now. I hope you will now be able to use the jQuery Validation Plug-in with ASP.NET Master Pages. More features about the jQuery Validation Plug-in can be learnt from here.
I hope this article was useful and I thank you for viewing it. The entire source code of this article can be downloaded over here.

0 comments:

 
Toggle Footer