Question

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?

Was it helpful?

Solution

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;
            }
        };
    });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top