- rule 1: length must be between 8 and 50 chars.
- rule 2: at least 3 of the 4 following rules:
- --------2a: at least one upper case
- --------2b: at least one lower case
- --------2c: at least one numeral
- --------2d: at least one non-alphanumeric.
I have a function which will take in two Strings (the password and the confirmation) and then return a boolean depending on if it verified. It also sets a label on my JavaFX screen to the error or confirmation message. It works fine, but the code seems cumbersome. any thoughts?
public boolean validatePassword(String newPass, String confirmPass)
{
if (newPass == null ||
confirmPass == null ||
newPass.length() == 0 ||
confirmPass.length() == 0 )
{
responseLabel.setText("");
return false;
}
boolean equalsRule = newPass.equals(confirmPass);
boolean lengthRule = newPass.length() >= 8 && newPass.length() <= 50;
boolean upperRule = !newPass.equals(newPass.toLowerCase());
boolean lowerRule = !newPass.equals(newPass.toUpperCase());
boolean numeralRule = newPass.matches("(.*)[0-9](.*)");
boolean nonAlphaRule = newPass.matches("(.*)[^A-Za-z0-9](.*)");
int ruleCount = (upperRule ? 1 : 0) + ( lowerRule ? 1 : 0) + ( numeralRule ? 1 : 0) + (nonAlphaRule ? 1 : 0);
if (ruleCount >= 3 && equalsRule && lengthRule)
{
responseLabel.setText("Password set successfully.");
responseLabel.setTextFill(Color.GREEN);
return true;
}
else
{
if (!equalsRule)
{
responseLabel.setText("Passwords must match.");
}
else if (ruleCount < 3 || !lengthRule)
{
responseLabel.setText("Password does not follow instructions above.");
}
responseLabel.setTextFill(Color.RED);
return false;
}
}