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!
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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$
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0