Password validation - adding additional requirments

倾然丶 夕夏残阳落幕 提交于 2019-12-23 03:53:11

问题


I have some code that currently checks for minimum and maximum lentgh. I want to also require uppercase, lowercase, special char, and numeric. Any suggestions on what to add to this or where I can find some examples? I've been Googling and looking thru this forum and have been trying to add the additional password requirments and have been unsuccessful.

This is what I want to require.

At least eight characters in length No more than 20 characters in length at least lower-case letter and one upper-case at least one special character from: !@#$%^&*()~`-=_+[]{}|:";',./<>? at least one number [0-9] character Cannot match the account login name or email address

My current password validation code

public static final int MIN_PASSWORD_LENGTH = 8;
public static final int MAX_PASSWORD_LENGTH = 20;

public static boolean isAcceptablePassword(String password)
{
    if(TextUtils.isEmpty(password))
        return false;

    int len = password.length();

    if(len < MIN_PASSWORD_LENGTH || len > MAX_PASSWORD_LENGTH)
        return false;

    for(int i = 0; i < len; i++)
    {
        char c = password.charAt(i);
        if (Character.isWhitespace(c))
            return false;
    }

    return true;
}

回答1:


When you're analyzing String data, you should erase the whitespaces on the right and left. This is done by the Strimg#trim function like this:

password = password.trim();

To analize every character of the String, you can transform it to a char array, so it will be easier to fulfill your requirements:

char[] arrPassword = password.toCharArray();

Now you can evaluate a char using these functions: Character#isUpperCase, Character#isLowerCase, Character#isDigit.

Last but not least, you can have a String with the special characters you need to check, and check if the actual character you're evaluating is inside that String. This could be achieved using String#indexOf and String#valueOf, this las one to convert the char to a String type.

Here is a code sample for all this explanation:

public static final String SPECIAL_CHARACTERS = "!@#$%^&*()~`-=_+[]{}|:\";',./<>?";
public static final int MIN_PASSWORD_LENGTH = 8;
public static final int MAX_PASSWORD_LENGTH = 20;

public static boolean isAcceptablePassword(String password) {
    if (TextUtils.isEmpty(password)) {
        System.out.println("empty string.");
        return false;
    }
    password = password.trim();
    int len = password.length();
    if(len < MIN_PASSWORD_LENGTH || len > MAX_PASSWORD_LENGTH) {
        System.out.println("wrong size, it must have at least 8 characters and less than 20.");
        return false;
    }
    char[] aC = password.toCharArray();
    for(char c : aC) {
        if (Character.isUpperCase(c)) {
            System.out.println(c + " is uppercase.");
        } else
        if (Character.isLowerCase(c)) {
            System.out.println(c + " is lowercase.");
        } else
        if (Character.isDigit(c)) {
            System.out.println(c + " is digit.");
        } else
        if (SPECIAL_CHARACTERS.indexOf(String.valueOf(c)) >= 0) {
            System.out.println(c + " is valid symbol.");
        } else {
            System.out.println(c + " is an invalid character in the password.");
            return false;
        }
    }
    return true;
}

The System.out.println(c + " is an invalid character in the password."); sentence is just to check the result of analyze the actual character.




回答2:


How about some good old regular expressions? This seems to work correctly, although might have made slip in the escaping for special char check

Pattern[] checks = {
        Pattern.compile("[!@#\\$%^&*()~`\\-=_+\\[\\]{}|:\\\";',\\./<>?]"),
        Pattern.compile("\\d+"), 
        Pattern.compile("[A-Z]+"),
        Pattern.compile("[a-z]+"), 
        Pattern.compile("^.{8,20}$") };

for (String test : new String[] { "password", "Password1",
        "Password1&", "toolongtoolongtoolong" }) {
    boolean ok = true;
    for (Pattern check : checks) {
        ok = ok && check.matcher(test).find();
    }
    System.out.println(test + " " + ok);
}



回答3:


Stephen is right with a bit of searching you would have found your answers easily around here. But the thread Stephen refers to is using a thirdparty library.

If you want to implement this yourself then before starting the for-loop initialize 4 booleans for your requirements with false. While looping check for all four requirements until one is true. Set the corresponding boolean to true.

How to check the 4 requirements:

  • The length req you already implemented.
  • Character(yourChar).isLowerCase()
  • Character(yourChar).isUpperCase()
  • Special character: see here: Java String Special character replacement - you can choose a similar approach

After the loop check for the 4 booleans and react accordingly.



来源:https://stackoverflow.com/questions/9962382/password-validation-adding-additional-requirments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!