:::: MENU ::::

Monday, June 1, 2009

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