Create new account I forgot my password    

Using jQuery Validation in ASP.NET Master Pages
Rating: 21 user(s) have rated this article Average rating: 3.8
Posted by: Suprotim Agarwal, on 5/1/2009, in category "jQuery and ASP.NET"
Views: this article has been read 55512 times
Abstract: jQuery 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 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

Using jQuery Validation in ASP.NET Master Pages
 
Sometime back, I had written an article on Using jQuery with the ASP.NET CustomValidator Control. 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.









Page copy protected against web site content infringement by Copyscape


How would you rate this article?

User Feedback
Comment posted by Buzzy on Friday, May 01, 2009 1:31 PM
Mate you are nothing short of a rockstar this article is TOP class (thumbsup)
Comment posted by anup hosur on Sunday, May 03, 2009 2:50 AM
nice article.. i read ur whole blog.. i always found new things.. great..
Comment posted by shihab on Tuesday, May 12, 2009 12:37 AM
Thanks
Comment posted by Frank on Tuesday, May 12, 2009 5:53 AM
Did you know that you don't have to include the vsdoc file?
it knows it automatically..
Comment posted by Suprotim Agarwal on Tuesday, May 12, 2009 12:17 PM
Frank: Yes, that was done by mistake. The reference has been removed. Thanks!
Comment posted by jerry qian on Tuesday, May 12, 2009 9:41 PM
good
Comment posted by Shail on Wednesday, May 13, 2009 3:17 AM
Hello Suprotim,
Nice article, once again hats off to you. Its always fun to read your article. Short and simple, but very useful for practical situations
Comment posted by Brian O'Connell on Wednesday, May 13, 2009 6:04 AM
I'm dissappointed at the approach .net article writers are taking when teaching the use of jQuery. One of jQuery's main selling points is that it facilitate "Unobtrusive" scripting, something unfortunately asp.net developers still ignore.

What it means is all script in external files, all web pages working without script. When it comes to form validation from what I can see the plugin you mention uses class attributes to validate by default. For example an input with a class attribute containing "required" will be validated as such. Same for "url", "email" etc. This means you can do without trying to get around the asp.net renaming mechanism and script unobtrusively.
Comment posted by salman on Wednesday, May 13, 2009 9:10 AM
hi,
good one.could you help me how can i display error message in red color?
Thanking you.
Comment posted by james taylor on Wednesday, May 13, 2009 10:34 AM
nice article.

but i have noticed that this will not work if you are using the jquery ui dialog as the dialog automatically moves the dialog div to the end of the dom outside of the master pages form element.
Comment posted by Taru on Thursday, May 14, 2009 7:42 AM
Good one.counld u tell me how can i validate phone number and display error message in red?
Comment posted by romel on Friday, May 15, 2009 9:39 AM
I agree with Brian O's comment, this validation could be done simpler w/o having to worry about the .Net renaming.  for instance you could have just write this on your script
<script>
....
     $('formnamehere').validate();
</script>

then in your input   <asp:TextBox ID="txtEmail" runat="server" class="required email"></asp:TextBox>
Comment posted by high class call girl on Monday, July 06, 2009 11:20 AM
Very impresive
Comment posted by Martin on Friday, October 09, 2009 3:45 AM
Nice one.
Comment posted by Onkar Shelar on Thursday, November 26, 2009 1:00 AM
I have used jQuery Validation Plug-in to Create an ASP.NET website with a Master Page and a Content Page. I hv follwed all the steps correctly given above...But it gives me error message as "Microsoft JScript runtime error: Object doesn't support this property or method" for the below code which is generated by runtime machine... Plz give me solution for the same...
$("#aspnetForm").validate({
            rules: {
                    ctl00_ContentPlaceHolderRight_txtFirstName: {
                        minlength: 2,
                        required: true
                      },
                    ctl00_ContentPlaceHolderRight_txtLastName: {                      
                        required: true,
                        minlength: 2
                      }
             },
             messages: {
                    ctl00_ContentPlaceHolderRight_txtFirstName:{
                        required: "* Required Field *",
                        minlength: "* Please enter atleast 2 characters *"
                       }
             }
         });        
Comment posted by Suprotim Agarwal on Thursday, November 26, 2009 2:15 AM
Onkar: Did you download the code and test it first?
Comment posted by waleed on Wednesday, December 02, 2009 5:53 PM
Asp.net Master page and JQuery reference – JS Inside Master Pages:
http://ledomoon.blogspot.com/2009/12/aspnet-master-page-and-jquery-reference.html
Comment posted by Manch on Monday, February 08, 2010 1:46 PM
I have textbox with ID="UserName" and ID="Password" inside asp:login control. It works fine if i have CssClass="required" but the problem is i cannot set the custom error message. Even the code below wont work where loginCtrl_UserName is the id generated for the control.
  messages: {
                   loginCtrl_UserName:{
                        required: "* Required Field *",
                        minlength: "* Please enter atleast 2 characters *"
                       }
             }
Comment posted by dami on Monday, March 01, 2010 9:00 PM
First of all, good job =)
Now i've a question, what if you need to validate two diferent forms?
I mean, obviously you can't put two forms in an asp .net page. But what would you do if you have separate groups of inputs used in diferent postabacks. Eg. A registration form in your content page  and a login in the master page. (I actually have that problem :P)
regards
D
Comment posted by anamika on Wednesday, March 10, 2010 2:40 AM
Very nice article,its help me.could u plz tell me how can i insert images and some user control in master page using jquer,like that i do using c#.is it possible or not.plz reply.
Comment posted by anamika on Wednesday, March 10, 2010 2:52 AM
Very nice article,its help me.could u plz tell me how can i insert images and some user control in master page using jquer,like that i do using c#.is it possible or not.plz reply.
Comment posted by gfj on Wednesday, June 23, 2010 5:28 AM
fghjfgh gh ghj gh
Comment posted by Ash on Wednesday, July 21, 2010 11:04 PM
Nice article!
I am getting the following JS error message:
Message: Expected identifier, string or number
Line: 28
Char: 21

Here is JS code:
          $(document).ready(function() {
            $("#EntryForm").validate({
                rules: {
                    <%=txtGroup.UniqueID %>: {  //This is the line the error is pointing to
                        minlength: 2,
                        required: true
                    },
                     <%=txtGroup.UniqueID %>: {                        
                        required: true
                    }
                },
                 messages: {
                    <%=txtGroup.UniqueID %>:{
                        required: "* Required Field *",
                        minlength: "* Please enter atleast 2 characters *"
                    }
                  }
            });
        });
Comment posted by lorena on Friday, August 06, 2010 12:19 AM
hola como estan

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel

NEWSLETTER