Check Password contains alphanumeric and special c

2020-07-18 06:30发布

How do you check if a string passwordText contains at least

  • 1 alphabet character
  • 1 number
  • 1 special character (a symbol)

标签: c#
7条回答
仙女界的扛把子
2楼-- · 2020-07-18 07:18

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.

查看更多
登录 后发表回答