views:

2586

answers:

6

Hi,

I have an input string and I want to verify that it contains:

  • Only letters or
  • Only letters and numbers or
  • Only letters, numbers or underscore

To clarify, I have 3 different cases in the code, each calling for different validation. What's the simplest way to achieve this in C#?

Thanks

+1  A: 

You can loop on the chars of string and check using the Char Method IsLetter but you can also do a trick using String method IndexOfAny to search other charaters that are not suppose to be in the string.

Baget
+15  A: 

Only letters:

Regex.IsMatch(input, @"^[a-zA-Z]+$");

Only letters and numbers:

Regex.IsMatch(input, @"^[a-zA-Z0-9]+$");

Only letters, numbers and underscore:

Regex.IsMatch(input, @"^[a-zA-Z0-9_]+$");
Philippe Leybaert
This assumes a latin alphabet, where Char.IsLetter allows for non-latin alphabets.
pb
+1  A: 

Iterate through strings characters and use functions of 'Char' called 'IsLetter' and 'IsDigit'.

If you need something more specific - use Regex class.

Arnis L.
+2  A: 

I think is a good case to use Regular Expressions:

public bool IsAlpha(string input)
{
    return Regex.IsMatch(input, "^[a-zA-Z]+$");
}

public bool IsAlphaNumeric(string input)
{
    return Regex.IsMatch(input, "^[a-zA-Z0-9]+$");
}

public bool IsAlphaNumericWithUnderscore(string input)
{
    return Regex.IsMatch(input, "^[a-zA-Z0-9_]+$");
}
CMS
Regex has static methods for this
Philippe Leybaert
Nice, I didn't remembered it, no VS on hand... editing...
CMS
+8  A: 

Letters only:

Regex.IsMatch(theString, @"^[\p{L}]+$");

Letters and numbers:

Regex.IsMatch(theString, @"^[\p{L}\p{N}]+$");

Letters, numbers and underscore:

Regex.IsMatch(theString, @"^[\w]+$");

Note, these patterns also match international characters (as opposed to using the a-z construct).

Fredrik Mörk
+1 for \w (and correct meaning of it)
cletus
+5  A: 
bool result = input.All(Char.IsLetter);

bool result = input.All(Char.IsLetterOrDigit);

bool result = input.All(c=>Char.IsLetterOrDigit(c) || c=='_');
Hasan Khan
Great approach - discovered you can use LINQ on strings and that you can use a method as a predicate.
Graphain