advanced web statistics

Use Client-Side JavaScript to Disable ASP.NET Validators

2/12/2008 1:03:56 AM

This came up this week on a project I am working on and now it will transcend to other projects.  I needed to rewrite some functionality utilizing client-side code.  Well, I could've done it server-side but I'm not a fan of unnecessary postbacks (or UpdatePanel "partial postbacks") so I decided to utilize JavaScript.

So I removed all the AutoPostBack="true"'s from the codebase and utilized my favorite property (Control.ClientID) to set the css display style to "none" or "" depending on which option was selected.  After all that was done I decided to test. Uh-oh, my RequiredFieldValidators were firing off since I was only using CSS* to hide / unhide my Panels. Instead of adding values to these controls to satisfy the expressions (which doesn't work all of the time (i.e. input type='file' or asp:FileUpload which don't allow the setting of a posted file as it is a security risk). I found out how to turn off validation.  It only took a little bit to add via codebehind.cs.

For this example, I have a CheckBox for checks that when clicked needs to disable a RequiredFieldValidator for CreditCard.  Stupid example I know.

check.Attributes.Add("onclick", string.Format("disable('{0}')", regexCreditCard.ClientID)); 

That will add the appropriate handler for client-side work. Now that that is out of the way, time for the actual disabling of the validator.

function disable(validatorId)
{
   var validator = document.getElementById(validatorId);
   ValidatorEnable(validator, false);

Easy. Now you can use .NET to implement tamper-proof validation and disable / enable via JavaScript for a richer user experience.

* Using "display: none" is much better than simply using "visibility: hidden" for what's it's worth (at least it was for me).  With "visibility: hidden" you can tell that something is supposed to be there. With "display: none" you can't.  So in summary, "visibility: hidden" results in the page calculating this div as part of the flow.  With "display: none", it's not even accounted for.  It's as if it were never there!

The more you know ;-)

AJAX, JavaScript

kick it on DotNetKicks.com

Leave a Comment

   

  Enter the text to proceed!