Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

verify password using regexes [duplicate]

Tags:

java

string

regex

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.

like image 370
Morten Due Christiansen Avatar asked Feb 11 '26 07:02

Morten Due Christiansen


2 Answers

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++;
like image 117
Nikolas Charalambidis Avatar answered Feb 13 '26 21:02

Nikolas Charalambidis


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.

like image 37
Toto Avatar answered Feb 13 '26 21:02

Toto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!