Java password check

I want to set up validation for a password field where the entered password must be at least 6 characters long and contain letters and numbers

private static final String PASSWORD_PATTERN = "^[A-Za-z0-9]{6}";

      

Then I have a method to check if the password is correct.

  public void validate() {

if(!password.matches(PASSWORD_PATTERN)) {
        this.addFieldError("password", "Password must contain 6 characters or more");
}

      

+3


source to share


2 answers


{6}

means exactly 6 characters, use {6,}

. I would also remove ^

from the regex because it is redundant. Also note that there is a predefined character class \w

that is a shortcut for [a-zA-Z_0-9]

if you are ok with _

in the password. In general it can be"\\w{6,}"



+12


source


A quick google revealed that what you want to do is a fairly common problem and people have tried it before.

For example see http://examples.javacodegeeks.com/core-java/util/regex/matcher/validate-password-with-java-regular-expression-example/



They also use regex to validate the password, but this is a bit tricky. This can provide some nice ideas on how to improve your code once it turns out that the alphanumeric 6 characters of passwords are not enough.

0


source







All Articles