One of the methods:
"\d{10}(\d{2})?"
Or you can be more explicit, at the cost of a little performance:
"^(\d{10}|\d{12})$"
The reason for binding in the second expression is described here :
If you are having problems with pattern matching constructs, try wrapping the expression "^ (" and ") $". For example, "a | ab" becomes "^ (a | ab) $".
Update
I was wondering why \d{10}|\d{12} does not work correctly, and decided to plunge into the source code for the validator to understand why this fails.
RegularExpressionValidator checks both the server and client side using the same regular expression, and in the case of \d{10}|\d{12} it fails on the client side for length 12, but works for length 10. Source code shows how the match is made:
var rx = new RegExp(val.validationexpression); var matches = rx.exec(value); return (matches != null && value == matches[0]);
Note that this is a regular expression A|B , but if A matches, B is never checked - the regular expression is not "greedy" about the pipe operation - it accepts the first match it finds. So the result of matching this regex is that the ten-digit match is successful even if you enter a 12-digit input. But then the value == matches[0] test fails because the match is not a complete string.
Reordering terms, i.e. the entry \d{12}|\d{10} , works because a longer match is checked first, and a shorter match is checked only if the match fails.
Lesson learned: It is recommended that you use explicit bindings when using the channel in the RegularExpressionValidator , so as not to worry about the order of the terms.
source share