Disabling ASP.NET validation with some JQuery magic

Original Post: http://blogs.planetcloud.co.uk/mygreatdiscovery/post/Disabling-ASPNET-validation-with-some-JQuery-magic.aspx

If you use ASP.NET Web Forms then it’s likely that you’ve used some of the built in validation controls. Typically we group our validation controls into a validation group, like so:

1 <asp:TextBox ID="txtFaxNumber" runat="server"
2 ValidationGroup="MyValidationGroup"/>

If we set the ValidationGroup property of a button to the same group (i.e. “MyValidationGroup”) it will prevent the form from submitting if the controls are not valid.

You may wish to enable or disable the validation based on the state of the page. For example, let’s say you have an optional data entry form that is only displayed if the user click a checkbox. If the optional form is visible then we want to enable validation. If not, the validation should be disabled, otherwise it will prevent the rest of your page from submitting.

To do this with Javascript (or in this case using jQuery) we have to loop through the Page_Validators array and find those in our validation group. We can then enable or disable the validator.

I wrote a simple helper function to do just that:

1 function SetValidator(groupName, state) {
2     $.each(Page_Validators, function(index, validator) {
3         if (validator.validationGroup == groupName) {
4             ValidatorEnable(validator, state);
5         }
6     });
7 }

Below is an example of enabling and disabling the validation group based on the state of a checkbox:

1 $(cb).click(function() {
2     SetValidator("EnterBillingAddress", !($(this).is(':checked')));
3 });

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s