Using jQuery validation with ASP.NET WebForms
AJAX, ASP.NET, jQuery, UI By Dave Ward. Updated November 24, 2009Note: This post is part of a long-running series of posts covering the union of jQuery and ASP.NET: jQuery for the ASP.NET Developer.
Topics in this series range all the way from using jQuery to enhance UpdatePanels to using jQuery up to completely manage rendering and interaction in the browser with ASP.NET only acting as a backend API. If the post you're viewing now is something that interests you, be sure to check out the rest of the posts in this series.

You’ve probably noticed that Jörn Zaefferer’s jQuery validation plugin has been gaining momentum in the ASP.NET community lately. Between Microsoft’s implied endorsement via ASP.NET MVC 2.0 integration and the plugin’s recent inclusion on the Microsoft AJAX CDN, adoption is only increasing. Unfortunately for those who don’t or can’t use ASP.NET MVC yet, using the validation plugin within WebForms applications can be tricky.
Because the WebForms Postback model requires that the entire page be contained within a single form element, form submissions that shouldn’t trigger validation are likely. ASP.NET’s built-in validation controls solve this with ValidationGroups and the CausesValidation property, but that doesn’t help if you’d prefer to use the jQuery validation plugin.
However, there are a couple relatively easy workarounds that make it possible to use the jQuery validation plugin on WebForms pages, without re-architecting the page or its forms. In this post, I’ll show you why the WebForms page structure is a problem, how to make jQuery validation work with it, and an example of implementing those workarounds.
Note: I want to preface this by saying that you should never rely entirely on client-side validation. The jQuery validation plugin can be a great replacement for the client-side part of the ASP.NET Validators, but it is not a complete replacement on its own. Use responsibly!
<form> over function
When it comes to using jQuery validation, the trouble with WebForms is that it requires all of the ASP.NET controls on a page to be contained within a single form element. That doesn’t lead to any problems in simple demos, but things are more complicated when it comes to real-world pages. They often require multiple logical forms on the same page, and that’s where the problems start.
For example, consider the common scenario of having both a login form and a customer information form on the same page. We’ve probably all seen something like this before:
<form id="form1" runat="server"> <fieldset> <legend>Returning customer? Login here</legend> <label for="Username">Email:</label> <asp:TextBox runat="server" ID="Username" /> <label for="Password">Password:</label> <asp:TextBox runat="server" ID="Password" TextMode="Password" /> <asp:Button runat="server" ID="Login" Text="Login" /> </fieldset> <fieldset id="BillingInfo"> <legend>New customer? Provide the following</legend> <label for="FirstName">First Name:</label> <asp:TextBox runat="server" ID="FirstName" CssClass="required" /> <label for="LastName">Last Name:</label> <asp:TextBox runat="server" ID="LastName" CssClass="required" /> <label for="Address">Address:</label> <asp:TextBox runat="server" ID="Address" CssClass="required" /> <label for="City">City:</label> <asp:TextBox runat="server" ID="City" CssClass="required" /> <label for="State">State:</label> <asp:TextBox runat="server" ID="State" CssClass="required" /> <label for="Zip">Zip:</label> <asp:TextBox runat="server" ID="Zip" CssClass="required" /> <asp:Button runat="server" ID="Order" Text="Submit Order" /> </fieldset> </form>
In most web frameworks, you would divide both logical forms into separate form elements, but WebForms requires both to remain joined within its single form element. This means that clicking either of the Button controls will submit both logical forms together.
Once applied to a form through its default usage, the jQuery validation plugin will attempt to validate all of the elements on that form any time it is submitted. That automation is usually handy, but it means users trying to submit our login form will be denied due to validation failing on the unrelated fields below.

Since using separate form elements containing WebForms controls isn’t realistic, we need to tackle this on the client-side and find a way to make jQuery validation more WebForms-friendly.
Taming jQuery validation
To remedy this problem, we first need to prevent the jQuery validation plugin from automatically triggering on every form submission. The initializer’s onsubmit property allows us to do just that:
$(document).ready(function() { // Initialize validation on the entire ASP.NET form $("#form1").validate({ // This prevents validation from running on every // form submission by default. onsubmit: false }); });
That fixes our problem of the login form triggering unwanted validation in the form below, but it creates another issue. Now, neither of the forms will validate when submitted.
Taking control with on-demand validation
Instead of relying on the plugin to automatically validate form submissions, you may also use a less widely known method for triggering the validation on-demand. When added to a page, one of the new methods that jQuery validation exposes on the jQuery object is valid().
When valid() is called on the jQuery object returned from selecting a “validated” form element, it will trigger validation on every field within the form and return a Boolean value indicating whether or not the form is valid.
$(document).ready(function() { $("#form1").validate({ onsubmit: false }); $("#Order").click(function(evt) { // Validate the form and retain the result. var isValid = $("#form1").valid(); // If the form didn't validate, prevent the // form submission. if (!isValid) evt.preventDefault(); }); });
At first glance, this code might look incomplete to you. We care about more than just preventing form submissions when the form fails validation; we must also indicate the validation errors to the user.
Fortunately, the valid() method has the very useful side effect of displaying the plugin’s configured validation errors for any fields it finds to fail validation.
From the user’s perspective, this implementation is the same as the original one using the default usage. This method just happens to also have the added benefit of actually allowing returning users to log in.
To be continued…
This solution is a good start, but has (at least) two flaws.
First, it doesn’t handle keyboard triggered form submissions. What happens if the user hits the enter key in one of the TextBoxes?
Second, what if we want to also validate the login form? If validation rules are added to that form’s fields, we’ll have exactly the opposite problem as what we started with. Valid submissions in the lower form will be prevented by validation failures on the upper form.
For solutions to both of those problems, be sure to read my followup post: Emulate ASP.NET WebForms validation groups with jQuery validation.
Download the Source
Similar posts
What do you think?
I appreciate all of your comments, but please try to stay on topic. If you have a question unrelated to this post, I recommend posting on the ASP.NET forums or Stack Overflow instead.
If you're replying to another comment, use the threading feature by clicking "Reply to this comment" before submitting your own.
8 Mentions Elsewhere
- uberVU - social comments
- Tweets that mention Using jQuery validation with ASP.NET WebForms | Encosia -- Topsy.com
- ASP.Net and jQuery Validate Plugin | Sébastien Hiticas
- links for 2009-12-01 | The Gryphin Experience
- Multi part jQuery validation continued.. | seekwaytech
- jrummell.ToString() » The State of xVal for WebForms
- jrummell.ToString() » xVal for WebForms – the Future
- jQuery validation with asp.net « Sharepoint. Kunskap. Upptäckter på resan.



I Like your post.
But i found this cool validation from Cedric Dugas
website: http://www.position-relative.net/
Demo: http://www.position-relative.net/creation/formValidator/
enjoy
were you able to use it with asp.net web form? I really like the effect and as i dont have real estate on the page i would like to use this tooltip validation error approach..
I solved this issue by extending the plugin to support validation groups, just like asp.net validators do.
Dave,
I’ve been considering replacing the existing validation in my project with this plugin for a few days now. Thanks for pointing out these pitfalls and your solution. I’m looking forward to part 2.
I was only looking at this myself last week. Looking forward to the second part.
Thanks,
Rich
The main problem with this plugin is that it forces you to validate within a form at all. The application I work on uses tons of AJAX, often inside modal dialogs. Submissions from these dialogs is via AJAX, and does not require a form. This greatly limits the usefulness of this plugin imo, as it only works for vanilla scenarios.
Feel free to correct me if I’m wrong, please! I’d be happy to know if there was a workaround that would allow submissions from outside a form tag.
I don’t know of a way to validate elements outside a form with this plugin (you’d think the .element() method would work, but it throws an error for elements outside a form).
It doesn’t hurt anything to wrap your modal’s input elements in a form though, if you want to be able to use the validation plugin. Having multiple forms on the page is okay as long only one is runat=”server” (I’m assuming we’re still talking about WebForms here).
You just have to remember to add a “return false;” in its onsubmit so that pressing enter in the fields doesn’t try to POST back to the page.
Steve, try to work around that by attaching the dialog to the form itself. Like so:
$(‘#UserEdit’).dialog({
autoOpen: false,
modal: true,
open: function(type, data) {
$(this).parent().appendTo(“#aspnetForm”);
}
});
I cut down the dialog code to just the relevant parts, but that will attach your dialog to the form when it opens, then the jquery validation should work for you.
Maybe I just missed this in your post, but what if you want to validate not only the “new customer” area, but also the “login” area depending on which button the user clicks? In the example above you’re just validating one of the sections, right? Wouldn’t it be useful to also check to see if they only entered a username and prompt for a password if they click the login button, for example?
From the plugin API it looks like you have the ability to add and remove rules. Would the solution to multiple section form validation be to simply add and remove rules based on which button was clicked before calling the valid() method? That seems kind of cumbersome, is there a better way? Or maybe I should just stick to validating one section of content per form :)
Whoops, sorry! I’m an idiot. Feel free to delete my comment above. I just read the To Be Continued… section again. Looking forward to the next post!
Don’t worry; you’re definitely not an idiot for having that concern. There’s an easier way than dynamically changing the validation rules (though that’s an interesting idea that I hadn’t thought of). Hopefully, I’ll get the next part out next week, covering that.
In asp.net(Ajax),How to use JQUERY.validate plug-in?
button in updatepannel,clicked, JQUERY.validate can deal with event of button?
Thanks for your great post. I have been looking for this solution for quite long. by the way I used kirs validation, but kris did you solve this two form scenario on this validation? Because when I used that cool validation I found the same problem. And how did Edvard Pitka solve the issue. Can we get some link where we can get the js where he used the validation group like .net does?
Thanks, I am waiting to see your second post on this topics.
Ashfaq
The followup post is published now: http://encosia.com/2009/11/24/asp-net-webforms-validation-groups-with-jquery-validation/
It took longer than I had anticipated; sorry for the delay.
Hey man ! You saved me !! rsrs
This solution is killer! Thanks for sharing such valuable information!
Very Good Article.
Thanks
JeevanSAthi
Thank you for your impeccable information.
Helped me a lot.
Keep it up
Thank you so much.
This is very helpful.
i want to validate a text box using jquery..anyone pls send me the code for textbox validation using jquery…
Very informative post. It’s really helpful for me and helped me lot to complete my task. Thanks for sharing with us. I had found another nice post over the internet which was also explained very well about Validating FileUpload control for specific file type and required field, for more details of this post check out this link…
http://mindstick.com/Articles/7d72a758-52bc-4242-922f-6b3914895d92/default.aspx?Validating+FileUpload+control+for+specific+file+type+and+required+field.
Thanks
Hi, Nice Job
In Sample Code u just used required keyword, i need to use equalTo to check password, would u explain how to use this method pleas ?
Thx
I don’t think you can use the CSS class approach for an equalTo check. You’ll need to use a regular jQuery Validation initializer, as shown in the plugin’s documentation.