检查密码包含字母数字和特殊字符

时间:2010-07-30 16:42:31

标签: c#

如何检查字符串passwordText是否至少包含

  • 1个字母字符
  • 1号
  • 1个特殊字符(符号)

7 个答案:

答案 0 :(得分:14)

试试这个:

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

虽然您可能希望通过“字母字符”,“数字”和“符号”更具体地说明您的意思,因为这些术语对不同的人意味着不同的事情,并且您不确定这些术语的定义是否匹配框架使用的定义。

我猜你用字母表示“a-z”或“A-Z”,用数字表示“0-9”,用符号表示任何其他可打印的ASCII字符。如果是这样,试试这个:

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));
}

如果实际上你指的是其他东西,那么相应地调整上述方法。

答案 1 :(得分:2)

使用RegEx将是最灵活的。您始终可以将其存储在资源文件中,并在不进行代码更改的情况下进行更改。

有关密码示例,请参阅以下内容;

http://regexlib.com/Search.aspx?k=password

答案 2 :(得分:1)

您可以使用String.IndexOfAny()来确定字符串中是否存在指定字符数组中的至少一个字符。

答案 3 :(得分:1)

strPassword.IndexOfAny(new char['!','@','#','$','%','^','&','*','(',')']);

您可以使用您正在寻找的字符/符号数组来运行它。如果它返回大于-1的任何值,那么你就得到了一个匹配。数字也是如此。

这将允许您准确定义您要查找的内容,并且如果您愿意,可以轻松地排除某些字符。

答案 4 :(得分:1)

这很简单;

Regex sampleRegex = new Regex(@"(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{2,})$");
boolean isStrongPassword= sampleRegex.IsMatch(givenPassword);

答案 5 :(得分:1)

对于一些非常简单的事情,我从之前使用的程序中获取了这个。

            //password rules 
            int minUpper = 3;
            int minLower = 3;
            int minLength = 8;
            int maxLength = 12;
            string allowedSpecials = "@#/.!')";

            //entered password
            string enteredPassword = "TEStpass123@";

            //get individual characters
            char[] characters = enteredPassword.ToCharArray();

            //checking variables

            int upper = 0;
            int lower = 0;
            int character = 0;
            int number = 0;
            int length = enteredPassword.Length;
            int illegalCharacters = 0;


            //check the entered password
            foreach (char enteredCharacters in characters)
            {
                if (char.IsUpper(enteredCharacters))
                {
                    upper = upper + 1;
                }
                else if (char.IsLower(enteredCharacters))
                {
                    lower = lower + 1;
                }
                else if (char.IsNumber(enteredCharacters))
                {
                    number = number + 1;
                }
                else if (allowedSpecials.Contains(enteredCharacters.ToString()))
                {
                    character = character + 1;
                }
                else
                {
                    illegalCharacters = illegalCharacters + 1;
                }

                // MessageBox.Show(chars.ToString());
            }

            if (upper < minUpper || lower < minLower || length < minLength || length > maxLength || illegalCharacters >=1)
            {
                MessageBox.Show("Something's not right, your password does not meet the minimum security criteria");
            }
            else
            {
                //code to proceed this step
            }

答案 6 :(得分:0)

这应该符合您的所有要求。它不使用正则表达式。

private bool TestPassword(string passwordText, int minimumLength=5, int maximumLength=12,int minimumNumbers=1, int minimumSpecialCharacters=1) {
    //Assumes that special characters are anything except upper and lower case letters and digits
    //Assumes that ASCII is being used (not suitable for many languages)

    int letters = 0;
    int digits = 0;
    int specialCharacters = 0;

    //Make sure there are enough total characters
    if (passwordText.Length < minimumLength)
    {
        ShowError("You must have at least " + minimumLength + " characters in your password.");
        return false;
    }
    //Make sure there are enough total characters
    if (passwordText.Length > maximumLength)
    {
        ShowError("You must have no more than " + maximumLength + " characters in your password.");
        return false;
    }

    foreach (var ch in passwordText)
    {
        if (char.IsLetter(ch)) letters++; //increment letters
        if (char.IsDigit(ch)) digits++; //increment digits

        //Test for only letters and numbers...
        if (!((ch > 47 && ch < 58) || (ch > 64 && ch < 91) || (ch > 96 && ch < 123)))
        {
            specialCharacters++;
        }
    }

    //Make sure there are enough digits
    if (digits < minimumNumbers)
    {
        ShowError("You must have at least " + minimumNumbers + " numbers in your password.");
        return false;
    }
    //Make sure there are enough special characters -- !(a-zA-Z0-9)
    if (specialCharacters < minimumSpecialCharacters)
    {
        ShowError("You must have at least " + minimumSpecialCharacters + " special characters (like @,$,%,#) in your password.");
        return false;
    }

    return true;        
}

private void ShowError(string errorMessage) {
    Console.WriteLine(errorMessage);
}

这是如何调用它的示例:

private void txtPassword_TextChanged(object sender, EventArgs e)
{
    bool temp = TestPassword(txtPassword.Text, 6, 10, 2, 1);
}

这不测试大写和小写字母的混合,这可能是优选的。为此,只需将char条件中断,其中(ch > 96 && ch < 123)是小写字母集,(ch > 64 && ch < 91)是大写字母。

正则表达式更短更简单(适合那些使用它的人)并且网上有很多例子,但这种方法更适合为用户定制反馈。