Could someone help me understand why this does not work
public boolean validatePassword(String pass){
final int MIN_LENGTH = 6;// Minimum length 6
// check if password is correct length and that it does not
// contain any invalid characters
if(pass.length() >= MIN_LENGTH && !pass.matches("(.*)[^.-_+!?=a-zA-Z0-9](.*)")){
// 4 rules, 3 should be fulfilled
// 1: Contain upper characters (A-Z)
// 2: Contain lower characters (a-z)
// 3: Contain numbers (0-9)
// 4: Contain following character . - _ + ! ? =
int ruleCount = 0; // counting fulfilled rules
if(pass.matches("(.*)[A-Z](.*)")) ruleCount++;
if(pass.matches("(.*)[a-z](.*)")) ruleCount++;
if(pass.matches("(.*)[0-9](.*)")) ruleCount++;
if(pass.matches("(.*)[.-_+!?=](.*)")) ruleCount++;
if(ruleCount >= 3) return true; // password verified
}
// password not verified
return false;
}
For some reason, it accepts password containing big and small letters and it also validates password for passwords containing numbers and small letters. But it should only validate if 3 of the for rules were fulfilled.
You have wrong the last check. Note that - defines the range in the [] group like [A-Z].
Don't forget to use \\ like here:
if(pass.matches("(.*)[.\\-_+!?=](.*)")) ruleCount++;
AFIK, matches is a method of Pattern, not String.
boolean b = Pattern.matches("a.*", text) ;
You should use:
if(Pattern.matches(".*[A-Z].*", pass)) ruleCount++;
and so on for other tests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With