Emulate ASP.NET validation groups with jQuery validation
AJAX, ASP.NET, JavaScript, jQuery, UI By Dave Ward; Updated August 5, 2011Note: 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.
In my most recent post, I demonstrated a workaround to allow using the jQuery validation plugin with WebForms pages. The basic idea was to trigger validation only on submissions that occurred within a single logical form, instead of catching submissions anywhere on WebForms’ all-encompassing physical form.
This approach worked fine for a single logical form, but wasn’t robust enough when handling validation for multiple logical forms on a single page. Additionally, it did not properly handle the enter key, allowing users to (perhaps accidentally) slip past validation if they simply hit the enter key within a TextBox.
In this post, we will continue by refining the solution from last time. So, if you haven’t read the previous post, familiarize yourself with it first. Specifically, this post will cover how to implement an analogue of WebForms’ ValidationGroup, use that to independently validate multiple form regions, handle the enter key, and refactor the final solution to minimize duplicated code.
ValidationGroups
In WebForms, we have the concept of a ValidationGroup to mitigate the issues that come with wrapping the entire page in a single form element. Whether right or wrong in principle, this scheme does a pretty good job of keeping the ASP.NET Validation controls from getting their wires crossed on complex forms.
However, using ASP.NET’s ValidationGroups requires that you use the WebForms validation controls, which generates quite a bit of cruft in your markup and injects two additional script references on your page.

If you’re like me, trying to trend away from client-heavy WebForms pages these side-effects are prohibitive.
Emulating Validation Groups
Though its implementation renders a bit messy on the client-side, the WebForms paradigm of a ValidationGroup is exactly what we need for segregating our physical form element into logical forms. In fact, I’m going to use the same nomenclature in this example (ValidationGroup and CausesValidation).
Using CSS classes as flags is a great way to emulate that concept in plain (X)HTML markup. Especially when using jQuery, CSS “flags” are a great way to tag elements with arbitrary attributes, that are easy to find with simple DOM selectors later. Taking the form shown in my previous post and tagging its fieldsets with a validationGroup class, we end up with this markup:
<fieldset class="validationGroup"> <legend>Returning customer? Login here</legend> <!-- Username and Password labels and inputs here --> </fieldset>
Not a very large change, but it allows us to keep these logical forms separate, both when performing validation and when initially setting up their validation triggers.
Creating a CausesValidation counterpart
ValidationGroups may control the organization of logical forms, but it’s the controls marked with the CausesValidation property that drive validation of those forms. In similar fashion, we need a way to indicate which elements should trigger our own emulation of WebForms’ grouped validation.
Sticking with the same naming scheme and CSS flagging technique, it makes sense to tag our Button controls with a .causesValidation class:
<fieldset class="validationGroup">
<legend>Returning customer? Login here</legend>
<!-- Username and Password labels and inputs here -->
<asp:Button runat="server" ID="Login" Text="Login"
CssClass="causesValidation" />
</fieldset>Now we just need to wire up functionality to make those causesValidation flags actually do something.
Acting on the validationGroup flag
With the markup modified to allow selective targeting of the validation groups, the next step is implementing validation functionality that leverages that targeting. Using jQuery’s powerful CSS-based selectors, that isn’t difficult:
$(document).ready(function () { $("#form1").validate({ onsubmit: false }); // Search for controls marked with the causesValidation flag // that are contained anywhere within elements marked as // validationGroups, and wire their click event up. $('.validationGroup .causesValidation').click(function (evt) { // Ascend from the button that triggered this click event // until we find a container element flagged with // .validationGroup and store a reference to that element. var $group = $(this).parents('.validationGroup'); var isValid = true; // Descending from that .validationGroup element, find any input // elements within it, iterate over them, and run validation on // each of them. $group.find(':input').each(function (i, item) { if (!$(item).valid()) isValid = false; }); if (!isValid) evt.preventDefault(); }); });
Note: For more explanation of any uncommented code above, be sure to see the previous post in this series. Those parts are explained in detail there.
This sets up a click event handler on any element flagged with the causesValidation class; the two Button controls in our case. When those raise click events, we start at the triggering element and use the parents() traversal method to search upward for the nearest parent flagged as a validationGroup.
In this example, that will find a reference to the fieldset which contains the Button control that triggers the click event (e.g. if the user clicks the Login Button, then $group will store a reference to the first fieldset element).
With that reference to the the logical form requiring validation, jQuery’s find() traversal method allows us to select a set of all the input elements within just that region of the page. Note that this will also include the Button control that triggered the event, but since the valid() method returns true for elements that don’t have validation rules configured, this doesn’t cause a problem.
From there, it’s straightforward to iterate over the appropriate input elements and validate each independently, using the valid() trick covered in the last post.
Handling the enter key
At this point, everything works pretty well, so long as the user clicks on the Button controls to submit the logical forms. Unfortunately, things fall apart if the user triggers form submission by pressing enter in one of the form fields.
One way to fix that would be to handle the form’s onsubmit event, determine if an element flagged with the causesValidation class triggered the submission, and then run through our validation first. That’s perfectly valid, but I avoid that because it tends to clash with other functionality that handles the event; the jQuery form plugin for example.
The alternative that I prefer is to handle a validated field’s onkeydown event. That way, if the element does need to trigger validation, it can do so early, and get out of the way quickly otherwise.
Using jQuery’s cross-browser normalized event object, testing for the enter key is not difficult at all. When handling keyboard related events, one property of that object is keyCode. This property will contain the ASCII character code of the key which triggered the event. In the case of the enter key, that keyCode is 13.
That in mind, this is a first iteration of adding enter key handling to our existing validation code:
// Select any input[type=text] elements within a validation group // and attach keydown handlers to all of them. $('.validationGroup :text').keydown(function (evt) { // Only execute validation if the key pressed was enter. if (evt.keyCode == 13) { // Validation code goes here. } });
Whether the form is submitted by clicking a button or hitting the enter key within one of our validation groups’ text fields, the appropriate inputs will be validated, error messages displayed if necessary, and submission will only continue if the form is valid.
Refactoring to eliminate duplication
After adding the keydown handler, everything works great, but it’s no good to have that validation code duplicated for both the click and keydown handlers. By passing around a reference to the jQuery event object, we can reuse the same validation code for both event types and make the code much more concise:
$(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 }); // Search for controls marked with the causesValidation flag // that are contained anywhere within elements marked as // validationGroups, and wire their click event up. $('.validationGroup .causesValidation').click(ValidateAndSubmit); // Select any input[type=text] elements within a validation group // and attach keydown handlers to all of them. $('.validationGroup :text').keydown(function (evt) { // Only execute validation if the key pressed was enter. if (evt.keyCode == 13) { ValidateAndSubmit(evt); } }); }); function ValidateAndSubmit(evt) { // Ascend from the button that triggered this click event // until we find a container element flagged with // .validationGroup and store a reference to that element. var $group = $(evt.currentTarget).parents('.validationGroup'); var isValid = true; // Descending from that .validationGroup element, find any input // elements within it, iterate over them, and run validation on // each of them. $group.find(':input').each(function (i, item) { if (!$(item).valid()) isValid = false; }); // If any fields failed validation, prevent the button's click // event from triggering form submission. if (!isValid) evt.preventDefault(); }
First, the validation code is refactored into a separate function: Validate.
Since it needs the ability to conditionally call preventDefault in order to stop form submission, the function accepts the event handlers’ jQuery event object as a parameter.
In fact, because $(this) is a reasonable place to begin the parents() traversal for either event that may call the method, very little refactoring is necessary.
The one thing that may seem strange is that the Validate function is being passed as a click handler without any parameters. The reason that this works is because the Validate function is defined with the same signature that jQuery expects. Because of that alignment, Validate will automatically be provided with the same event object that we’ve been using in anonymous callback functions thus far.
Calculated readability
Note that I attached keydown handlers to all of the text inputs within a validation group, regardless of whether or not they are actually validated fields. Similarly, you may have noticed that the click handler finds every input element within its validation group, even if those inputs aren’t marked for validation. This may seem like an oversight, but it’s an intended readability compromise.
You could modify the selector to be more precise, selecting only fields flagged with validation classes (e.g. required, email, number, etc). However, this gets messy when you consider the wide variety of classes that are valid for tagging elements with jQuery validation functionality.
Rather than be precisely specific, I rely on the fact that jQuery validation’s valid() method returns true for elements which are not configured for validation. So, even if we do end up checking the validation status of a few irrelevant input fields, it won’t adversely impact the outcome of the validation process.
There are performance penalties to performing validation on these unnecessary elements, but it is negligible for a reasonably sized form. The ancillary inputs would have to number in the thousands before the penalty were noticeable, at which no one will probably ever successfully complete it anyway!
Conclusion
There are even more enhancements to be had, but I think this brings the solution to a point that it’s useful. With multiple logical forms handled and the perennially pesky enter key tamed, the majority of use cases should be covered.
The most troublesome issue still remaining is that care should be taken to avoid nesting container elements with the validationGroup class on them. Otherwise, the Validate() function will search “too high” and possibly hinge validation on input fields that are not intended. It’s an edge case (fixable if necessary), but something to keep in mind.
Another edge case is that, unlike the ASP.NET Validators, these validation groups can’t overlap. For my own use, this has never been an issue. I’m curious if that’s a real-world problem for any of you.
Finally, an entirely different approach well worth considering is John Rummell’s xVal for Webforms. Using Data Annotations to specify validation rules is gaining a lot of popularity, so it’s worth investigating options like this one. At the minimum, it will help you be more familiar with how validation is handled in ASP.NET MVC.
Hope that helps. Be sure to take a look at the source download to see everything pulled together and one extra usability feature that I didn’t have time to cover.
Get the source
If you’d like to browse through a complete working example of what’s been covered in this post, take a look at the companion project at GitHub. Or, if you’d like to download the entire project and run it in Visual Studio to see it in action yourself, grab the ZIP archive.
WebForms-jQuery-Validation on GitHubWebForms-jQuery-Validation.zip
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.
5 Mentions Elsewhere
- Tweets that mention Emulate ASP.NET validation groups with jQuery validation | Encosia -- Topsy.com
- uberVU - social comments
- Emulate ASP.NET validation groups with jQuery validation | Encosia
- Update – ASP.Net and jQuery Validate Plugin | Sébastien Hiticas
- Jquery validate分组验证 « 辣不死



To fix the first issue, you should be able to use the closest function in place of the parents function.
That’s a great point; thanks for the comment.
My solution was to use .parents(‘.validationGroup:first’), but .closest(‘.validationGroup’) is more concise and readable both.
Another excellent post, Dave. Thanks for the link!
Hi Dave,
Awesome and a really helpful post as usual.
Thanks !!!
That’s useful stuff…
But validatio has now evolved way beyond this.
In ASP.NET MVC 2.0, you can activate all of your server-side validation on the client-side — by adding one line of code!
http://www.timacheson.com/Blog/2009/oct/mvc2_and_vs2010_preview
Unfortunately, the overwhelming majority of ASP.NET code is still WebForms (and probably will be for some time to come). Rewriting an entire project so that it can use MVC 2′s validation model is more than one line of code!
Yes, obviously legacy products are subject to the usual constraints.
It’s useful to be aware of the powerful new features in ASP.NET MVC 2.0 to make the case for adoption in new projects. MS MVC2 is so much better, there’s also a compelling case for migrating legacy products to the new platform.
Of course, you can still use conventional WebForms alongside the new structure in an ASP.NET MVC web app. Developers could use the old and new approaches in the project during the transition, if it helps.
The thing to keep in mind is that WebForms isn’t “legacy” by a long shot. The majority of new ASP.NET projects, even in 2010, will be continue to be WebForms.
Don’t worry, I don’t think anybody is calling ASP.NET a legacy technology just yet! Though there may well be legacy systems on it.
“A legacy system is an old method, technology, computer system, or application program that continues to be used … even though newer technology or more efficient methods of performing a task are now available.”
http://en.wikipedia.org/wiki/Legacy_system
I was looking for something like this. Thanks for the article and I’ll try it out for sure in my next project.
There is 2 issues to take into account,
1) Don’t set UseSubmitionBehavior=false on your asp.net’s submit buttons, it won’t work.
2) If you have multiple submit buttons on a page (that’s why we need the grouping feature to begin with) then pressing enter on input fields from the second group on the page will initiate the validation on gropu1 and you wont be able to submit the form, that’s because where there are several submit buttons on a page browser will treat your enter event as if the first button on the page has been clicked. this is a common problem in asp.net. so i have improved a litle bit the code to handle this situation, here it is:
The code I posted handles the enter key correctly. When you hit enter in an input, it will ascend from that element, find the first parent flagged as a validationGroup, then validate the elements in that group only.
That’s correct it will handle the enter event and validate this group only, and if group2 is not valid it will correctly prevent the form from submit. But if group2 “is” valid, the browser will automatically fire a click event for the submit button of Group1, and if the first group is not valid the form will not submit, i have tried it. also read this: http://www.4guysfromrolla.com/articles/010908-1.aspx
I see what you’re saying now, and you’re right. I’m surprised I missed that in the example. Thanks for pointing it out.
This simple fix takes care of it cleanly:
Using click() to trigger validation (and submission) through the input’s click event prevents that problematic behavior when the form is submitted with enter.
Thank you so much. I love this article and its comments.
I made some changes to fit my need.
1) I like the ‘Enter’ behavior of checking, not just ‘Tab’.
2) I need to auto scroll to the first invalid item and focus it.
Welcome Modification!
How about instead of:
var $nextInput = $(this).nextAll(‘:input:first’);
Just:
var $nextInput = $(this).next(‘:input’);
Neither nextAll(“:input:first”) nor next(“:input”) work since my form uses an ordered list for the mark-up like so:
So if I hit enter in smth1, it won’t pick up smth2 for the next element – it’ll just pick itself.
In your specific structure, I think you could use:
That’s pretty much what I did, except I used find(“:input”) instead of children, but either one will work just fine in this case.
You are good ;-)
I’m not sure that evt.preventDefault() alone will prevent group1 submit button from being clicked, because the browser raises a separate click event for the submit button of group1. i have tried it and so far i couldn’t get it to work unless i explicitly ignore click events from “different” groups.
The key is that it always prevents an enter submission from proceeding, rather than trying to catch errant/fake click events. So, even if you hit enter on an input element preceding a submit, it no-ops the enter event, then triggers a click event on that submit instead. That way the event is only raised once, and on the correct submit every time.
Dave,
It looks as if this doesn’t work in the following case :
where I want to validate Zip for digits but I’m not checking whether or not it is a required field. All validation via the class attribute that is not ‘required’ is treated as if it is required. If I validate the form this does not happen.
It looks like you’ve run into a bug in the validation plugin.
The Zip field flagged as just “digits” does pass validation when it’s empty, if the regular validator.form() method is used to validate, yet $(‘#Zip’).valid() returns false.
It probably stems from the same issue reported here: http://plugins.jquery.com/node/11803
Try this to ignore invalid but empty fields that are not required.
I ran into this bug for a slightly different reason: 2 telephone number fields where either one is required, but not both. Hence the custom dependency callbacks e.g.:
When coupled with the same call back for the mobile telephone and some additional logic to make these re-validate on keyup of either box, this works perfectly but ONLY for the dynamic validation (e.g. form submitted with no telephone numbers and then telephone numbers entered so error messages appear and disappear as they should).
The problem comes with when you actually submit the form. The following code is the problem:
$group.find(':input').each(function (i, item) { if (!$(item).valid()) isValid = false; });Because $(item).valid() returns false (not valid) for the $(‘.vTelephoneHome’) element, even when the callback function returns false (i.e. the field should NOT be required).
Peter’s solution above would not work because items are only ‘required’ under certain circumstances and to my knowledge don’t get given the required class dynamically.
I’m looking at a pretty hacky work around on this at the moment, but I just wondered if anybody had found a more elegant and fix-all workaround to this bug.
I believe I commented on this above on “12:02 pm – June 9, 2011″. Do an in-page search on that exact time stamp string and you’ll find my reply.
Hope that helps.
In the end, I worked around this by not using dependency callbacks at all because doing so means you run into the bug mentioned in this thread.
Instead, I completely avoided by adding new custom validators which do the same thing (probably the more correct way to implement this in any case.
So that’s an additional validator like:
Then you have to add the validation to the elements as normal:
(The mobile validator intentionally has empty error message so you only get the error once and it’s always the first one i.e. the one nearer the TelephoneHome control)
… and just for completeness you’d need to trigger the validation so it validates on keyup of either box e.g.:
So in short, avoid this bug by keeping as far away from it as possible and not using the dependency callback for the required validtion methos
thks man, It’s very useful.
Hi,
This is cool.
I want to extend this functionality. I have various fields in the panel like textbox, dropdownlist etc and i want to validate that any one of the field is filled before user than click the search button. If none of the field is filled that user should see message at the top of panel. (Like validation summary in asp.net)
Any ideas how can i accomplish that using jquery?
Regards
Mac
You can do that using the validation plugin. There are a variety of options you can set to specify where validation errors are displayed and how they should be styled. The documentation covers that pretty well here: http://docs.jquery.com/Plugins/Validation/validate#toptions
Hi – I have multiple fieldsets, similar to your demo. I can’t figure out how I can add validation rules that are specific to each form section (i.e., fieldset). Also, I would like have a ‘validation summary’ section (listing each error) for each fieldset, but I can’t get errorContainer/errorLabelContainer to work.
Any help is greatly appreciated! Thanks!
What if I have another button on the page for a ‘Back’ function, which uses server side code to redirect the user. How do I stop it from causing the validation?
Thanks.
(Newbie)
you can use “cancel” css class set to back button like this
If you followed the example, only buttons tagged with the causesValidation class should trigger client-side validation. Just make sure your redirect button doesn’t have that class on it.
Dave, fantastic post!
You helped me very quickly as your post can be literally pasted straight in without modification. You’re a legend. I am modernising one of my customer’s legacy systems which is in web forms.
I made a small change to further make the browser focus/jump to the first element that fails validation (just like the default validate() routine does)..
A small change too…
Another tiny enhancement to my changes too. I had to swap the order of the evt.preventDefault() and the focus() lines as I was getting some problems with the form firing half a millisecond after the focus() line completed, with the preventDefault() firing first, this is resolved. The updated code is:
Just further on this guys, I don’t bother to implement the Enter key handling here with my own messy script, because there is a much easier/cleaner way to just get web forms to generate that code automatically. It took me a long time to sift through Google a while back to find this, but I’ve used it heaps now and it works really reliably.
All you need to do is wrap an asp:Panel around the form that you want the default button behaviour active on and then add a DefaultButton parameter to specify which button you want the Enter key to initiate!
Further, you also don’t need to specifically use a “fieldset” element to implement “validationGroup” as per Rick’s example above, that can actually be any containing element. And as an asp:Panel renders into a div, it also makes it ideal to use.
So, to solve both problems at once (enter key press and add “validationGroup”) I simply wrap a panel like this around any forms:
etc etc
Aaron, spot on, you’ve just saved me hours or re-factoring the code to do just this. Badly needed to place the submit button outside of the panel/fieldset.
Glad I read all the replies….really nice work here all. Keep it up…
Hey Dave – your code is excellent and I use it extensively on my site using divs as ValidationGroups – works great – HOWEVER, I have a jquery-ui dialog that this is not working in – If I remove the div (“studentEntryForm”) from the dialog and place directly on the page, the “ValidateAndSubmit” works fine, but when it is in the dialog, it errors in the jquery validate js here:
valid: function() { if ($(this[0]).is('form')) { return this.validate().form(); } else { var valid = true; var validator = $(this[0].form).validate(); this.each(function() { valid &= validator.element(this); }); return valid; } }It bombs on the last line there “valid &= validator.element(this)”. It is saying that “validator” is undefined at this point. Have you….or anyone else tried to use this in a jquery ui dialog?
I believe the Dialog plugin moves its elements around in the DOM, to the very bottom of the page in a dynamically generated container that’s outside of the ASP.NET form. That’s probably the source of your trouble, since you’re testing for .is(‘form’).
Great post!!!
Just one thing to add, in the latest version of Chrome I found it was submitting the form with it’s own built in enter key helper, which bypassed the ajax that needs to run first before submitting. To confirm as a test, if you change the key helper code in jQuery to say your shift key (16) to submit instead, Chrome wasn’t auto-submitting.
The solution is to add this in your form tag:
Thanks!
Looks like my code was stripped out, one more time…
If you add (onsubmit=”return false;”) to your form tag, it will fix the Chrome auto-submit.
Hi
Thank you for nice code. Can you please tell me how to handle checkbox, radiobutton, checkboxlist, radiobutton in asp.net with this code?
Thanks
this is great solution. I am using it but there is one problem with on enter validation.
The problem is with password inputs and the following code:
// Select any input[type=text] elements within a validation group
// and attach keydown handlers to all of them.
$(‘.validationGroup :text’).keydown(function (evt) {
// Only execute validation if the key pressed was enter.
if (evt.keyCode == 13) {
ValidateAndSubmit(evt);
}
});
as you only search for text inputs, the validation will not fire after clicking enter being focused on input password. I fixed it with this code:
$(‘.valGrpUserRegistration :input’).each(function(i, item) {
if($(item).is(‘:text’) || $(item).is(‘:password’)) {
$(item).keydown(function (evt) {
// Only execute validation if the key pressed was enter.
if (evt.keyCode == 13) {
ValidateAndSubmit(evt);
}
});
}
});
as you can see all inputs are found but only text and passwords are have keydown event assigned.
That, so very good the code I feel, it by my English, but I have a doubt, if I call to a function in submit and the validation is false, so that method enters, I do not understand so that? They can help me please.
Thanks for this validation group and comment solution…
great work…:)
Hi I downloaded your script and run perfectly fine but it doesn’t seem to work with a checkbox. Any advice on this? Thanks!
Change:
To:
And it should correctly validate checkboxes too.
Sorry for double post, may I know how to use validate option like minlength(), range(), etc with your code? Thanks!
Initializing the rules works the same way as normal. When you call
$('#form1').validate(), you can pass in an object with validation rules, messages, etc. The same as you’ll find in the plugin’s documentation.Hi Dave, appreciate your time to answer my questions and I have to say this is something that I’ve been cracking my head on. But I notice in your download example, you do not call $(‘#form1′).validate(), instead you indicate those rules in the css class. Is that the way how your example works? I’d love to do it that way as it’s cleaner. Hope to hear from you again, thanks!
Both the explicit object literal in .validate() and the CSS-based rules are interchangeable. That’s a feature jQuery Validation itself offers. The problem with the CSS-based rules is that they’re only available for simple validations like email, required, and digits, and that they don’t allow you to specify a custom validation error message. When you progress beyond the simple cases, those CSS-based rules are usually insufficient, and then you need to begin using the
rulesandmessagesparameters described here: http://docs.jquery.com/Plugins/Validation/validate#optionsThanks for your reply again. As I was previously using the jquery validation with rules and it works on my webforms but I was struggling with validation with multiple forms due to a few pop up windows I have on Masterpage. Now with your code, multiple forms works but validation rules like minlength (for password), equalTo (password confirm) no longer works. Only the basic rules like required, email and digits works. You may want to double check on this or update your sample source code with these rules examples. I’m sure this nice solution of yours can benefits thousands out there. Once again, thanks for sharing such a wonderful solution :)
Thanks for your article. I am wondering what is the reason to use jQuery validation in web forms since most validation can be handled by the standard ASP.NET validation controls? A nice thing about the standard ASP.NET validation controls is that they do both the server side and client side. But if we start using jQuery validation plugin on client side, we still have to write validation on server side — so there is duplication. So generally what is this buying us?
The driving motivation here is that it’s more and more common to be using ASP.NET WebForms pages that primarily communicate with services after they’re rendered. In that case, you’re still limited to a single form on the page and have to work around that somehow (e.g. validation groups), but aren’t necessarily submitting data via postbacks. So, the old postback-centric validator controls aren’t helpful.
The validator controls also inject quite a bit more per-field cruft in the page than the jQuery plugin requires, so this helps trim down the page size a bit.
Hey guys,
Did you manage to fix that issue with dialog? I am working on a project where the dialog is quite heavily used and it stops us from using the jquery validate plugin :/
Thanks,
Lukasz
Hi Lukasz,
I think this article would give you an approach to manage with a dialog modal:
http://www.codeproject.com/KB/ajax/jQuery-Modal-Dialogs.aspx
good luck
Rodrigo
I have this validating perfectly with one exception, it validates my submit button and changes the class. My button is styled with a css class. When I click it, the button is validated and loses it’s css class. Any idea how to ignore this? I’ve tried using “ignore: ‘.ignore’” in the validation and then adding the “ignore” as another class to the button.
thanks!
That’s strange. I’ve never had trouble with jQuery Validation trying to validate submit buttons. You could explicitly avoid submit type inputs by modifying the relevant selector like this:
Thanks Dave! That did it. Man, I appreciate the quick reply.
Great post covers my issues, wow .NET 3.5 winforms what a punch on, for jQuery and Ajax, MVC is so much simpler and easier and quicker, but that which does not kill us makes us grow stronger.
will let you down in cases where the field is not required but has other rules defined.
In these cases, valid() actually returns false when it should return true. Mind you that .valid() relies on .element() and that’s what I would recommend using as .element() itself will return undefined in these case instead of false. So I would change your code as follows:
Hi Dave, First of all great site ! love your approach. OK then i’m very new to JS and ASP.NET i want to know how do i change this, to only check for to input items not the entire page .
That’s the idea behind the
.validationGroupclass shown above. If you tag the sub-section of the page that you want to limit validation to and use this approach for the validation, you’ll only validate input items inside that container.Have you downloaded the example project and taken a look at how it works?
Thanks for the fast response. Yes i download the project, but the validation it’s trigering on not required fields also. Any ideas in how i can go over that?
I just downloaded the sample, gave it a try, and I’m not seeing anything like that happening. Can you be more specific about what you mean?
Thanks for the very informative article Dave. Can you advice how to implement this functionality while using a jQuery UI modal dialog ?
You would define your .validationGroup(s) where needed, including the #dialog div that will be wrapped by jQuery UI. Also, keep in mind that the validation is triggered by elements which have .causesValidation class, so your JQuery UI dialog button will need to have this class if you want the elements inside the dialog to be validated before closing it for instance.
Now, the intricacy of using JQuery UI dialog is that by default it takes the wrapped dialog out of the since it’s appended before the tag. This is a problem as jquery-validation plugin relies on elements being inside the or they will not get validated.
To mitigate this issue, make sure to place the dialog inside the when you open it:
Ah … my tags got taken out of the post. Here’s the paragraph with the tags I was referring to:
Now, the intricacy of using JQuery UI dialog is that by default it takes the wrapped dialog out of the
<form></form>since it’s appended before the
</body>tag. This is a problem as jquery-validation plugin relies on elements being inside the
<form></form>or they will not get validated.
To mitigate this issue, make sure to place the dialog inside the form when you open it:
First of all i thanking you for a wonder full solution. I’m searching for one of this article a while.As I was previously using the jquery validation with rules and it works on my webforms but I was struggling with validation with multiple forms due to a few pop up windows I have on Masterpage. Now with your code, multiple forms works but validation rules like minlength , equalTo no longer works. Only the basic rules like required, email and digits works. Could you please double check on this or update your sample source code with these rules examples. I’m sure this nice solution of yours can benefits thousands out there. Once again, thanks for sharing such a wonderful solution :)
You can combine rules defined in the .validate constructor with rules declared via CSS classes. So, you could add a minlength validation to the example in this post, for example:
I updated the example code on GitHub with an example of that, if you want to look at a working example.
Hi Dev thanks for quick reply, i want one more help in this scenario. I’m using jquery tab menu and using user controls containing textboxes, dropdownlist,et..
inside each tab. when I’m using this type of validation its working only in the first tab and remaining tabs are submitting without validation.I’m expecting a best solution from you. Thanks in advance :)
This should work fine in tabs. Make sure none of your selectors are excluding the elements you want to validate.
Excellent article and a great help! I was nearing the end of a project and dreading implementing a tonne of ASP.NET validation controls. This really makes the whole thing so quick and simple to implement, thank you!
How do I add click events to each of the submit buttons?
This article helped me out so much – thank you.;
Hi!
Nice to see that this article is still helpful are so long, so thanks for that.
I was wondering if you ever implemented a way to reset validation errors only within the validationGroup? jQuery validate supports a resetForm method, but I couldn’t find away to reset only a validation group.
Thanks, Schmulik.