check alphanumeric characters in string in c#
Try this one:
public static Boolean isAlphaNumeric(string strToCheck)
{
Regex rg = new Regex(@"^[a-zA-Z0-9\s,]*$");
return rg.IsMatch(strToCheck);
}
It's more undestandable, if you specify in regex, what your string SHOULD contain, and not what it MUST NOT.
In the example above:
- ^ - means start of the string
- []* - could contain any number of characters between brackets
- a-zA-Z0-9 - any alphanumeric characters
- \s - any space characters (space/tab/etc.)
- , - commas
- $ - end of the string
public static bool IsAlphaNumeric(string strToCheck)
{
return strToCheck.All(char.IsLetterOrDigit);
}
10001 New York, NY
contains a comma and spaces -- not alphanumeric
You need to adjust your expression to allow commas and spaces.
Also, you will probably want to rename the function so that it is clear to other developers that it is more of a validator than an isAlphaNumeric() function.