Reputation: 641
I have a textbox in which I'm using the event TextChanged to check if the string is valid with RegEx and show a messagebox if it isnt. When testing the regex I have with online regex tool such as http://regexpal.com/, it seems to be working fine. But when I run my code, it's not working as expected. I'm never seeing the messagebox show up. Any help would be appreciated. My regex is suppose to check any digits from 0-5 before the "." with two decimals if any.
private void txtValInput_TextChanged(object sender, TextChangedEventArgs e)
{
string input = (sender as TextBox).Text; //1234567
if(!Regex.IsMatch(input, @"^\d{1,5}|\d{0,5}\.\d{1,2}$"))
{
MessageBox.Show("Error!, check and try again");
}
}
Upvotes: 1
Views: 19023
Reputation: 11480
The reason it isn't working is because you haven't encompassed your Regular Expression within ()
. Without that identifier it isn't able anchor your syntax correctly.
You would want your Expression to look like this:
@"^(\d{1,5}|\d{0,5}\.\d{1,2})$
Keep in mind you may have also added additional complexity to your Expression.
To elaborate:
^
: Will grab the first character or line.\d
: Will grab all the numeric characters.$
: Will stop at end of line or last character.I'd like to take a second with that second one. If you actually do \d+
it will grab all numeric characters and all that precede afterwards. Which may make your request slightly easier; but I'm unsure of what you are searching.
Hopefully that helps, I see a Grey 1 Answer Box so someone else posted so you should easily find a resolution Calvin.
Upvotes: 1
Reputation: 13631
You need to add the ()
so the regex is properly anchored, otherwise your example matches because the regex is only checking whether there are one to five digits at the start of the string - anything could come after.
@"^(\d{1,5}|\d{0,5}\.\d{1,2})$"
Upvotes: 2