views:

201

answers:

2

I wanted to write a regular expression using the ASP.Net RegExp validator that would ensure a field contains only numeric and decimal values, and at least one character.

^[0-9]{1,40}(\.[0-9]{1,2})?$

Essentially: [0-9]{1,40} - meaning at least one to 40 numeric characters.

The ASP.Net regexp validator does not fire for an empty field - where there is not at least one character.

Work-around: using the custom validator with the regexp check in Javascript:

 function validateMinTrans(sender, args) {
        var error = true;
        var txtMinTrans = document.getElementById('TxtMinTrans');
        var regexp = new RegExp("^[0-9]{1,40}(\.[0-9]{1,2})?$");
        if (txtMinTrans.value.match(regexp)) {
            alert("good");
        }
        else {
            alert("bad");
        }

        if (error)
            args.IsValid = false;
        else
            args.IsValid = true;
    }

Thus, I don't even have to check txtMinTrans.length == 0.

Wondering if anyone else has experienced this.

+1  A: 

ASP.NET validators don't generally fire for empty fields; you need to add a RequiredFieldValidator if you want to check for that. There's no problem with having two validators on the same field.

This allows you to have optional fields: just having the RegularExpressionValidator alone means "is either empty or matches this regular expression".

Matt Bishop
A: 

The Regex validator does indeed not run unless the field has a value. However, you can also put a RequiredFieldValidator pointing to the same TextBox control, so both will handle their own responsibilities against it - empty and pattern.

Rex M
Yeah, that's what I've had to do in the past... but but just outlining the difference in the way the same expression performs differently in the between the two.
ElHaix
@ElHaix so... what's the actual question?
Rex M
Well, basically I was pointing out the difference in how the regex works between RequiredFieldValidator and a custom JS regex validation.
ElHaix