Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check Password contains alphanumeric and special character

Tags:

c#

How do you check if a string passwordText contains at least

  • 1 alphabet character
  • 1 number
  • 1 special character (a symbol)
like image 473
001 Avatar asked Jul 30 '10 16:07

001


1 Answers

Try this:

bool result =
   passwordText.Any(c => char.IsLetter(c)) &&
   passwordText.Any(c => char.IsDigit(c)) &&
   passwordText.Any(c => char.IsSymbol(c));

Though you might want to be a little more specific about what you mean by 'alphabet character', 'number' and 'symbol' because these terms mean different things to different people and it's not certain that your definition of these terms matches the definitions the framework uses.

I would guess that by letter you mean 'a-z' or 'A-Z', by digit you mean '0-9' and by symbol you mean any other printable ASCII character. If so, try this:

static bool IsLetter(char c)
{
    return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}

static bool IsDigit(char c)
{
    return c >= '0' && c <= '9';
}

static bool IsSymbol(char c)
{
    return c > 32 && c < 127 && !IsDigit(c) && !IsLetter(c);
}

static bool IsValidPassword(string password)
{
    return
       password.Any(c => IsLetter(c)) &&
       password.Any(c => IsDigit(c)) &&
       password.Any(c => IsSymbol(c));
}

If in fact you mean something else then adjust the above methods accordingly.

like image 57
Mark Byers Avatar answered Oct 12 '22 22:10

Mark Byers