Introduction
Ever used a custom or required field validator and found that they don't fire when the field is empty? This simple "hack" will enable you to fire the clientvalidationfunction
or evaluate the regular expression even when the fields are empty.
At the bottom of your page, (you can use the Page.RegisterStartupScript
for this) add the following two functions:
<script language="javascript">
function CustomValidatorEvaluateIsValid(val) {
var value = "";
if (typeof(val.controltovalidate) == "string") {
value = ValidatorGetValue(val.controltovalidate);
}
var args = { Value:value, IsValid:true };
if (typeof(val.clientvalidationfunction) == "string") {
eval(val.clientvalidationfunction + "(val, args) ;");
}
return args.IsValid;
}
function RegularExpressionValidatorEvaluateIsValid(val) {
var value = ValidatorGetValue(val.controltovalidate);
var rx = new RegExp(val.validationexpression);
var matches = rx.exec(value);
return (matches != null && value == matches[0]);
}
</script>
These functions also exist in the WebUIValidation.js of (in my case) the aspnet_cient\system_web\1_1_4322 folder, but because they are declared after the WebUIValidation.js include tag, these will get fired instead of the normal ones.
Note the commented lines. You could also comment these lines in the actual WebUIValidation.js file but an update of these files would overwrite this. That's why I've put them at the bottom of the WebForms using this feature. (Only tested in IE 6.0.)
Hope it helps someone!