views:

193

answers:

2

Hello all,

When I use the .Net RegularExpressionsValidator control the Validation expression matches EXACT text. When I say this I mean, for the string I give it to validate, if it deviates from the regex pattern at all the string does not validate.

ex: (([0-1][0-9])|([2][0-3])):([0-5][0-9]) if given in the RegularExpressionsValidator control will only match strings like -> 12:00, 07:15, 23:59 but does not match strings 12:00foo, bar23:00, foobar.

Now, when I use the Regex class in the code behind and give it the same regular expression it matches all strings that contain a match and any other characters.

ex: (Using the same regular expression as the last example) if I use the Regex class the following strings will match -> 12:00, 07:15, 23:59 AND 12:00foo (contains a match), bar23:00 (contains a match).

Is there a reason that they are treated differently and is there a way to mimic the same behavior as the RegularExpressionValidator control?

Thanks in Advance!

+5  A: 

What's happening is that the regex validator is processing your string as a line of text. It is implicitly putting in the ^ and $ matchers at the beginning of the regex.

It's like saying:

^(([0-1][0-9])|([2][0-3])):([0-5][0-9])$

The above expression in the Regex Class will produce the same result as the validator control.

Gavin Miller
A: 

One simple, universal way to get your regular expression to match a string exactly is to force it to match from the beginning to the end of the string like this:

^pattern$
RossFabricant