ASP.Net RegularExpression Validator - Parsing bug
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 c开发者_开发技巧ustom 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.
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".
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.
精彩评论