Over 8 years of industry-standard experience.

Posts Tagged ‘RegularExpressionValidator’

Is .NET’s RegularExpressionValidator Broken?

Thursday, October 30th, 2008

At the office yesterday, I spent a few hours trying to figure out why .NET’s RegularExpressionValidator would not require the user to enter a valid zip code (5 digits, or \d{5} in PCRE).  I spent a lot of time checking that the fields were connected, that the ValidationGroup was set and many other things.

I came to the conclusion that the problem was not my markup, so I spent some time using Firebug to step through the page-generated validation script.  After rooting around in the script, I found a fair-sized flaw in the logic.  Below, you will find the “stack trace” in bold blue.

function Page_ClientValidate(validationGroup) {
    Page_InvalidControlToBeFocused = null;
    if (typeof(Page_Validators) == "undefined") {
        return true;

    var i;
    for (i = 0; i < Page_Validators.length; i++) {
        ValidatorValidate(Page_Validators[i], validationGroup, null);

    Page_BlockSubmit = !Page_IsValid;
    return Page_IsValid;

function ValidatorValidate(val, validationGroup, event) {
    val.isvalid = true;
    if ((typeof(val.enabled) == "undefined" || val.enabled != false) &&
        IsValidationGroupMatch(val, validationGroup)) {
        if (typeof(val.evaluationfunction) == "function") {
            val.isvalid = val.evaluationfunction(val);
            if (!val.isvalid && Page_InvalidControlToBeFocused == null &&
                typeof(val.focusOnError) == "string" && val.focusOnError == "t") {
                ValidatorSetFocus(val, event);

function RegularExpressionValidatorEvaluateIsValid(val) {
    var value = ValidatorGetValue(val.controltovalidate);
    if (ValidatorTrim(value).length == 0)
        return true;
    var rx = new RegExp(val.validationexpression);
    var matches = rx.exec(value);
    return (matches != null && value == matches[0]);

function ValidatorTrim(s) {
    var m = s.match(/^\s*(\S+(\s+\S+)*)\s*$/);
    return (m == null) ? "" : m[1];

What you see at the very end is a regular expression that trims any white space from the beginning and end of a value.  For general use, this is a great idea.  If you take a step back, however, you will see that it’s doing this with the value of a field. Secondly, you might notice that it also assumes an empty string satisfies the regular expression.

This size of this defect is horrible.  Does anyone know if there is a way to fix the JS in .NET?  For the moment, the simplest solution I have come up with is to add a RequiredFieldValidator to ensure that the field is not completely empty.

To all the .NET developers out there, good luck.

Hero Development Inc.© 2008

Powered by WordPress
Entries (RSS) and Comments (RSS).