Java's standard regular expression classes like Pattern and Matcher only support CharSequence which includes String and StringBuffer but not char[]. And, for security reasons, it is important to never convert a password into a String. It is advisable to keep the password in a char array. So, how do you enforce password rules on a char array. The below code is a sample of how you will need to implement password rules:
public static boolean isPasswordPatternValid(char[] password) {
if (password == null || password.length < 8) {
return false;
}
boolean hasDigit = false;
boolean hasLower = false;
boolean hasUpper = false;
boolean hasSpecial = false;
char[] specialChars = new char[] {'~','@','#','$','%','^','&','*','(',')'};
for (int i = 0; i < password.length; i++) {
if (!hasDigit && Character.isDigit(password[i])) {
hasDigit = true;
continue;
}
if (!hasLower && Character.isLowerCase(password[i])) {
hasLower = true;
continue;
}
if (!hasUpper && Character.isUpperCase(password[i])) {
hasUpper = true;
continue;
}
if (!hasSpecial) {
for (int j = 0; j < specialChars.length; j++) {
if (password[i] == specialChars[j]) {
hasSpecial = true;
break;
}
}
}
}
return true;
}