Reputation: 139
I am trying to validate a text box in Visual Studio to be either the character M or F. I have a few other validations with regex set in a similar fashion which are all working correctly. However, with this one, it still allows me to use ANY letter in the text box. What is wrong with this code?
public static bool IsGender(string gender)
{
bool validGender = true;
string _genderRegEx = @"^\:|m|M|f|F|$";
if ((!Regex.Match(gender, _genderRegEx).Success))
{
MessageBox.Show("Gender must be either M or F.");
validGender = false;
}
return validGender;
}
Upvotes: 0
Views: 32
Reputation: 44841
Your regex is incorrect. You have:
@"^\:|m|M|f|F|$"
The |
symbols mean boolean OR
. Because you don't have any parentheses to group parts of your regex, the ^
only goes with \:
, and the $
is by itself. As a result, your regex matches any of the following:
^
) plus :
m
or M
f
or F
$
).Every string has an ending, so every string matches.
A correct regex would be:
@"^[mMfF]$"
This matches the start of the string (^
), followed by exactly one of m
, M
, f
, or F
, followed by the end of the string ($
).
Upvotes: 2