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;
}
When you’re analyzing
Stringdata, you should erase the whitespaces on the right and left. This is done by theStrimg#trimfunction like this:To analize every character of the String, you can transform it to a char array, so it will be easier to fulfill your requirements:
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#indexOfandString#valueOf, this las one to convert the char to a String type.Here is a code sample for all this explanation:
The
System.out.println(c + " is an invalid character in the password.");sentence is just to check the result of analyze the actual character.