How can I validate a string to only allow alphanumeric characters in it?

How can I validate a string using Regular Expressions to only allow alphanumeric characters in it?

(I don't want to allow for any spaces either).


Solution 1:

In .NET 4.0 you can use LINQ:

if (yourText.All(char.IsLetterOrDigit))
{
    //just letters and digits.
}

yourText.All will stop execute and return false the first time char.IsLetterOrDigit reports false since the contract of All cannot be fulfilled then.

Note! this answer do not strictly check alphanumerics (which typically is A-Z, a-z and 0-9). This answer allows local characters like åäö.

Update 2018-01-29

The syntax above only works when you use a single method that has a single argument of the correct type (in this case char).

To use multiple conditions, you need to write like this:

if (yourText.All(x => char.IsLetterOrDigit(x) || char.IsWhiteSpace(x)))
{
}

Solution 2:

Use the following expression:

^[a-zA-Z0-9]*$

ie:

using System.Text.RegularExpressions;

Regex r = new Regex("^[a-zA-Z0-9]*$");
if (r.IsMatch(SomeString)) {
  ...
}