3

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.

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183

2 Answers2

3

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++;
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
2

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.

Toto
  • 89,455
  • 62
  • 89
  • 125
  • thank you for the answer. but didn't do any difference however. But found out with testing that for some reason a pattern of small letters and either a capital or a number, it gets a positive match on "(.*)[.-_+!?=](.*)" which is puzzling to me – Morten Due Christiansen Feb 21 '16 at 18:11
  • 1
    They're the same method. `String#matches()` method calls `Pattern.matches()` under the hood. – Alan Moore Feb 22 '16 at 06:57