Turning Off ASP.Net Validators
In true web forms style, what should be simple is more difficult than it should be, at least in my opinion. Today I needed the following simple UI.
Simple enough right? Pick something from the list or type your own text. The JavaScript to enable and disable the controls wasn’t too bad. It’s pretty un-interesting, so I’ll just skip over it. What I found surprising was the validators were still firing even though the controls were disabled. I wasn’t expecting it, but oh well. Now to turn off the control’s validators.
I found a lot of examples that looked like the following:
var myVal = document.getElementById('somevalidatorid');
ValidatorEnable(myVal, false);
That’s nice, but I really don’t want to have to know each and every validator id for each control. It would also make the generic enable/disable code really tightly coupled to the controls we’re trying to disable.
Luckily, we can just find all the validators manually. jQuery can help us out, but isn’t really required.
function enableAllValidatorsFor(control,shouldEnable){
var validators = $.grep(Page_Validators,
function(validator,i){
return validator.controltovalidate == control.id;
});
$.each(validators, function(i,validator) {
ValidatorEnable(validator,shouldEnable);
});
// the validator callout leaves the error
// class on the control after the validator gets
// disabled, so we have to clean that up.
if(!shouldEnable){
$(control).removeClass("error");
}
}
The last little bit of code removes a CSS class that is set via a validator callout. It is tightly coupled with our pages, so you probably won’t need it, or will need a different class name. However, even though it is tightly coupled, it’s couple to all the pages and not the instance of the control it is disabling. We probably could find the validtor callouts used by the validator controls being disabled and remove any of the error classes they apply, but that didn’t seem necessary right now.
Something else interesting is the inconsistency of the jQuery API in this case. In the “grep” and “each” method the order of the arguments is reversed in the callback.
For grep you have:
function grepCallback(item, index){}
..and for each you have:
function eachCallback(index,item){}
Comments(2)
It will be much easier combined with jQuery.
@Jack Yea, I didn’t see a reason to not use jQuery here. One thing I didn’t mention in the article, but probably should go back and add, is you need to also disable the validators on the server during any postback. It will forget and fail the server side validation if you don’t.