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 06:53

This is pretty simple ;

Regex sampleRegex = new Regex(@"(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{2,})$");
boolean isStrongPassword= sampleRegex.IsMatch(givenPassword);
查看更多
Melony?
3楼-- · 2020-07-18 06:55

For something quite simple, I took this from a program I used previously.

            //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
            }
查看更多
聊天终结者
4楼-- · 2020-07-18 07:04

Using RegEx is going to be most flexible. You can always store it in a resource file and change it without making code changes.

See the below for some password examples;

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

查看更多
ゆ 、 Hurt°
5楼-- · 2020-07-18 07:11
strPassword.IndexOfAny(new char['!','@','#','$','%','^','&','*','(',')']);

You can run that with an array of the characters/symbols you're looking for. If it returns anything larger than -1, you've got a match. The same can be done with numbers.

This will allow you to define exactly what you're looking for, and will easily allow you to exclude certain characters if you wish.

查看更多
Root(大扎)
6楼-- · 2020-07-18 07:15

You can use String.IndexOfAny() to determine if at least once character in a specified character array exists in the string.

查看更多
一夜七次
7楼-- · 2020-07-18 07:15

This should meet all of your requirements. It does not use regex.

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

This is an example of how to call it:

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

This does not test for a mixture of upper and lower case letters, which may be preferred. To do so, simply break the char condition up where (ch > 96 && ch < 123) is the set of lower case letters and (ch > 64 && ch < 91) are upper case.

Regex is shorter and simpler (for those who are good with it) and there are many examples online, but this method is better for customizing feedback for the user.

查看更多
登录 后发表回答