password validation not working correctly

Tags: ,



I’m using this code for validating whether a user entered all characters. There were several solutions offered in this forum, but unable to find answer for my problem.

Problem-1: when the password entered is of this type “aaBB11@@”, it validates and returns ok, where as “11aaBB@@” gives error. Tested with different patterns but unable to find the correct string.

Problem-2: can we have a boolean (true / false) as a return value. I’m guessing matcher.matches() is boolean, but I’m not sure.

    public boolean isValidPassword(final String password) {

    Pattern pattern;
    Matcher matcher;

    final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\S+$).{6,}$";

    pattern = Pattern.compile(PASSWORD_PATTERN);
    matcher = pattern.matcher(password);

    return matcher.matches();

}

Can’t figure out where I’m going wrong!

Answer

Have a look at Regex101

The top right, it breaks down each part of the Regex into step.

Also in the bottom right there are references to Regex patterns – You can even test your regex live and export working code.



Source: stackoverflow