Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Fire CustomValidator or RegularExpressionValidator ClientValidationFunction always!

0.00/5 (No votes)
22 Mar 2005 1  
Override the WebUIValidation.js function to fire the custom or regular expression validator even when the field is empty.

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">

//OVERRIDE THE NORMAL VALIDATOR FRAMEWORK

function CustomValidatorEvaluateIsValid(val) {
    var value = "";
    if (typeof(val.controltovalidate) == "string") {
        value = ValidatorGetValue(val.controltovalidate);
        //make it fire always

        //if (ValidatorTrim(value).length == 0)

        //    return true;

    }
    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);
    //make it fire always

    //if (ValidatorTrim(value).length == 0)

    //    return true;        

    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!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here