Using jQuery with the ASP.NET CustomValidator Control

Posted by: Suprotim Agarwal , on 4/9/2009, in Category jQuery and ASP.NET
Views: 95756
Abstract: I have absolutely no hesitation in stating that jQuery is the most popular JavaScript and AJAX framework available. Now-a-days, developers caught by this wave, tend to ease their client-side development by using jQuery wherever and whenever they can. I came across a similar requirement when one of my clients requested me a POC (Proof of Concept) of using jQuery with the ASP.NET CustomValidator validation control. This article discusses how to validate an Address field using the ASP.NET CustomValidator and jQuery.
Using jQuery with the ASP.NET CustomValidator Control
 
I have absolutely no hesitation in stating that jQuery is the most popular JavaScript and AJAX framework available. Now-a-days, developers caught by this wave, tend to ease their client-side development by using jQuery wherever and whenever they can. I came across a similar requirement when one of my clients requested me a POC (Proof of Concept) of using jQuery with the ASP.NET CustomValidator validation control. This article discusses how to validate an Address field using the ASP.NET CustomValidator and jQuery.
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 the latest version of jQuery 1.3.2 and jQuery 1.3.2 Visual Studio 2008 Autocomplete documentation.
A Brief note about the CustomValidator control
The CustomValidator control performs a field’s validation based on custom validation logic that you provide. Using this control, you can write server-side validation code using C# or VB.NET as well client-side validation code using JavaScript, to check user input.
Note: Always remember to perform server-side validation.
Since the focus of this article is to integrate jQuery and the ASP.NET CustomValidator control, I will jump straight to the basics of ClientSide Validation with the CustomValidator control. When we do client-side validation, the JavaScript function to be used looks similar to the following:
function ClientSideValidation(source, args)
where ‘source’ is a reference to the validation control and ‘args’ is the object whose ‘Value’ property represents the data to be validated. The args.IsValid property determines if the data validates (true) or does not validate (false).
The ‘ClientFunctionName’ property of the CustomValidator control associates your client-side code with the CustomValidator.
Typically, this is how you would do Client-Side Validation using JavaScript
    <asp:Textbox id="TextBox1" runat="server" text=""></asp:Textbox>
    <asp:CustomValidator id="custV" runat="server"
      ControlToValidate = "TextBox1"
      ErrorMessage = "Minimum 4 characters required"
      ClientValidationFunction="CheckLength" >
    </asp:CustomValidator>
...
<script type="text/javascript">
     function CheckLength(sender, args) {
         args.IsValid = (args.Value.length >= 4);
     }
</script> 
   
</head>
Let us see how to do the same using jQuery.
Assuming you have downloaded the jQuery files stated in the beginning of this article, create a reference to the jQuery 1.3.2 file in the <head> section of your page as shown below:
<head runat="server">
    <title>CustomValidator using jQuery</title>
 
    <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
   
Now drag and drop a TextBox, a Button control and the CustomValidator control to the page. Set the TextMode=”Multiline” property of the TextBox to convert it to a <textarea>. The TextBox will be used by users to enter ‘Address’ information. The requirement is that the minimum characters to be entered in the TextBox should be 10, Maximum characters should not exceed 50 and that the TextBox allows only AlphaNumeric characters along with a few special characters like &().
Disclaimer: A CustomValidator control is used when the other ASP.NET validation controls does not suit your needs. However the ‘Address’ field requirement described above, is possible to achieve using the RegularExpression Validator control. Having said that, the focus of this article is to just demonstrate how to use jQuery with the CustomValidator control, and to be honest, I felt this example is a good candidate to demonstrate the code brevity achieved using jQuery, while validating the Address field. Moving ahead…
After setting up a few properties on the CustomValidator control, the markup will look similar to the following:
    <asp:Label ID="Label1" runat="server" Text="Address : "></asp:Label>
    <asp:TextBox ID="TextBox1" TextMode="MultiLine" runat="server" CssClass='txtAdd'/>
    <br />
        <asp:CustomValidator ID="CustomValidator1" runat="server" Display="Dynamic"
        ErrorMessage="Field cannot be blank<br/>Minimum 10, Maximum 50 chars allowed<br/>Only AlphaNumeric and Special Characters like &()- allowed"
        ClientValidationFunction="chkAddressField"
            onservervalidate="CustomValidator1_ServerValidate" >
        </asp:CustomValidator>
    <br />
    <asp:Button ID="Button1" runat="server" Text="Submit" />
   </div>  
C#
    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        // Write your Server side validation code here.
    }
VB.NET
      Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As ServerValidateEventArgs)
            ' Write your Server side validation code here.
      End Sub
Observe that the ClientValidationFunction is pointing to the chkAddressField() method. This is the client-side Method that will check user input before the page is submitted. The server-side method has been created but kept empty since that is not the focus of this article.
It’s time to introduce jQuery now. Write the following code in the <head> section of your page
<head runat="server">
    <title>CustomValidator using jQuery</title>
 
    <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
   
    <script type="text/javascript">
        function chkAddressField(sender, args) {
            args.IsValid = false;
            $(".txtAdd").each(function() {
                if (/^[A-Za-z0-9&()-]{10,50}$/.test(this.value)) {
                    args.IsValid = true;
                }              
            });           
        }
    </script>
</head>
In the code above, to start with, we are setting the args.IsValid property to ‘false’. The property is set to ‘true’ only if the text entered in the textbox (with class ‘txtAdd’) passes the regex validation.
If the user enters characters less than 10 or greater than 50 or a character that’s not allowed, then the validation occurs at client side and prevents the user from submitting the form as shown below
jQuery CustomValidator
And that's it! Well I hope that gave you some idea of using jQuery with the CustomValidator control. I will be sharing more examples with you as I continue exploring jQuery with ASP.NET. Until then, happy coding! The entire source code of this article can be downloaded from here

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for ten consecutive times. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Rajendra on Thursday, April 9, 2009 11:17 PM
Dear
A good article.
But, you have not explained the JQuery code.Please explain the line : (".txtAdd").each(function() {
                if (/^[A-Za-z0-9&()-]{10,50}$/.test(this.value)
Especially I am unable to understand the following code ".test(this.value)".
Please also tell if the same code is to be written using Javascript , then how ?

Waiting for your early reply.

Thanks
Comment posted by anup hosur on Friday, April 10, 2009 1:27 AM
nice article.. i really like the way u explain..
Comment posted by Suprotim Agarwal on Tuesday, April 14, 2009 12:41 PM
Rajendra: That's a built in function which tests the value of the textbox against the regular expression and returns a bool. this.value represents the value of the control with the class .txtAdd

Anup: Thanks!
Comment posted by abhilashca on Wednesday, April 29, 2009 6:08 AM
I must say. Nice article.
So simple.
When I downloaded the sample omly. I came to know about the password protection. BTW, Im a registered user. Can you tell me where can I find the password?
Thanks.
Comment posted by Carol on Wednesday, April 29, 2009 8:00 AM
The password has been mailed to you at your hotmail id. Thanks.
Comment posted by Lars Nielsen on Saturday, May 2, 2009 11:36 AM
I don't quite see how JQuery helps in this case.  Would it not be more robust to use args.Value rather than the selector ".txtAdd"?  You can use regular Javascript to test if args.Value matches the regular expression, so wouldn't this do the same thing:

function chkAddressField(sender, args) {
  args.IsValid = false
  if (args.Value.match(/^[A-Za-z0-9&()-]{10,50}$/)
  {
      args.IsValid = true
  }
}
Comment posted by Rajendra Kumar A.R on Sunday, May 31, 2009 2:53 AM
hi this is a nice article thanks for sending me hope u will send these types of new points to me bye
Comment posted by fern on Sunday, May 31, 2009 10:52 AM
when i debug the login.aspx, then login task got administer website, click it.select security, got message unable to connect to SQL Server database.why?
Comment posted by Varun on Monday, June 1, 2009 11:03 AM
Hi Carol, i have subscribed however don't have the password. Please send me the password.
Comment posted by kumar on Tuesday, June 2, 2009 10:59 AM
JQuery has been greatly implemented by you.http://www.planetsourcecode.in
Comment posted by Sid on Wednesday, June 3, 2009 2:45 AM
I am sorry, but I didn't liked the article at all. jquery is just a tool, and should be used only when appropriate. In this case it's not. Many "cargo cult" programmers don't understand it, and following your article, they will start writing "$(".txtAdd").each(function() {" instead of simply using the "sender" parameter.
Comment posted by Suprotim Agarwal on Thursday, June 4, 2009 2:59 AM
Sid: Thanks for your comments. .txtAdd is just another way of selecting controls having the same class. You may not require each textbox to be validated, so take action only on those textboxes where the class=txtAdd
Comment posted by явеявевя on Saturday, August 1, 2009 7:10 PM
асдвяеяве
Comment posted by cat on Sunday, August 2, 2009 4:15 AM
Thank you so much, It really helped..
Comment posted by sgfsdgfds on Wednesday, March 14, 2012 8:54 AM
dfsfsfs

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

Tags

JQUERY COOKBOOK

jQuery CookBook