Using jQuery with the ASP.NET CustomValidator Control
Posted by: Suprotim Agarwal ,
on 4/9/2009,
in
Category jQuery and ASP.NET
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.
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
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.
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!
Was this article worth reading? Share it with fellow developers too. Thanks!
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 Sixteen consecutive years. 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