DeepakVerma
DeepakVerma

Reputation: 99

checking for alphanumeric and special characters in a string

The requirement in my project is to check a string for following conditions:

  1. It must contain at least one letter (a-z or A-Z)
  2. It must contain at least one number (0-9)
  3. It must not contain any special characters.

Is there any regular expression that can match all these conditions ?

Here is the code I am using for this

private bool IsValidFormat(string str)
{
   Regex rgx = new Regex(@"^[A-Za-z]+\d+.*$");
   return rgx.IsMatch(str);
}

It is working for point# 1 and 2 above but it is allowing special characters. Any help would be appreciated.

Upvotes: 2

Views: 2813

Answers (1)

Mark Cilia Vincenti
Mark Cilia Vincenti

Reputation: 1614

The following change allows at least one letter, at least one digit and no other characters. The order of letters and digits is not important, unlike the solution offered in the OP where it requires that it starts with a letters and ends with numbers.

private bool IsValidFormat(string str)
{
   Regex rgx = new Regex(@"^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$");
   return rgx.IsMatch(str);
}

Upvotes: 3

Related Questions