How can we access the Asp.NET Validators like Required Field,Regular Expression,etc.. using JQuery?
How can we control their display and customize them using Jquery?
-
Your question is quite broad. Can you reduce it to specific problems you might be encountering?Frédéric Hamidi– Frédéric Hamidi2013-03-29 10:24:32 +00:00Commented Mar 29, 2013 at 10:24
-
Like Take for instance with help of Jquery we can play with Asp.Net controls,for example we can remove,insert,delete,clear etc.. but with Asp.Net validators it is very difficult to access them using Jquery I cannot customize them using Jquery??Madhavan NR– Madhavan NR2013-03-29 10:37:18 +00:00Commented Mar 29, 2013 at 10:37
1 Answer
In short, yes, you can access validators from Javascript (you do not actually need jQuery to do that), provided of course client-side validation is enabled (i.e. there is at least one enabled and visible validator in the page with its EnableClientScript property set to true).
The validator objects are available in the global Page_Validators array. You can disable or enable individual validators with ValidatorEnable(), and force validation with ValidatorValidate(). This MSDN article provides more information about the client-side validation API.
Arbitrary customization can be achieved by rebinding the validation method of a validator. This old answer of mine documents the process in plain Javascript, with jQuery it gives something like:
if (window.Page_Validators) {
$.each(window.Page_Validators, function(index, validator) {
validator.__old_evaluationfunction = validator.evaluationfunction;
validator.evaluationfunction = function(value) {
var element = validator.controltovalidate;
if (!validator.__old_evaluationfunction(value)) {
// Validation failed - turn 'element' red, scream at the user, etc.
return false;
} else {
// Validation succeeded - restore 'element' to its normal state.
return true;
}
};
});
}