Java regular expression (validating password)

Asked

Viewed 1,978 times

2

I need a regular expression to validate the following password:

The password must contain at least one element of each:

  1. More than 6 characters;
  2. Upper and lower case letters;
  3. Numbers;
  4. Special characters.

Actually, I have this:

if(senha.matches("(^|$)[a-z]+(^|$)[0-9]")) {
    JOptionPane.showMessageDialog(null, senha.matches("(^|$)[a-z]+(^|$)[0-9]"));
}

else {
    JOptionPane.showMessageDialog(null, senha.matches("(^|$)[a-z]+(^|$)[0-9]"));
}

1 answer

3


Does it have to be regular expression? I ask this because determining that using regular expression is necessary seems to me to be a case of XY problem.

If the use of regular expressions is not mandatory, you can do this:

public static boolean senhaForte(String senha) {
    if (senha.length() < 6) return false;

    boolean achouNumero = false;
    boolean achouMaiuscula = false;
    boolean achouMinuscula = false;
    boolean achouSimbolo = false;
    for (char c : senha.toCharArray()) {
         if (c >= '0' && c <= '9') {
             achouNumero = true;
         } else if (c >= 'A' && c <= 'Z') {
             achouMaiuscula = true;
         } else if (c >= 'a' && c <= 'z') {
             achouMinuscula = true;
         } else {
             achouSimbolo = true;
         }
    }
    return achouNumero && achouMaiuscula && achouMinuscula && achouSimbolo;
}

And that still has the advantage that if you need to change the criteria of what is considered a strong password, it’s much easier to move it than in a regular expression.

  • Thank you very much friend, it was very valuable your help, the code ran beautiful :D Really, this way I do not need to use regular expressions to validate, much easier the understanding.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.