I am trying to validate strings according to various regular expressions; however, if whitespace characters get added to the end of the string, they do not get flagged anymore.
if (Regex.IsMatch(literal.Value.ToString().ToLower(), @"^\+?[0-9\-\(\)\.\/]{8,20}$")
{
//Logic
}
In the following piece of code; the X-value gets flagged but the Z-value does not.
string x = "0337350670"; // Gets flagged
string z = "0337350670 "; // Does not get flagged
Should I change my regular expression or is there a way to validate against a part of the string?
You can just Trim
your string to remove trailing whitespaces from both sides.
Also, many special regex characters aren't special anymore inside a character class (-
still is, but is escaped if you put it like so: [...-]
).
Regex.IsMatch(literal.Value.ToString().ToLower().Trim(),
@"^\+?[0-9()./-]{8,20}$"
Removing ^$
would work too, but be aware this would allow strings composed of more than 20 digits in a row: you don't check the maximum length anymore (anything containing [0-9()./-]{8}
would match).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With