Home > Enterprise >  Password validation in Java using RegEx
Password validation in Java using RegEx

Time:03-21

I need a regular expression to check that if a password contains:

  • [1,6] uppercase/lowercase characters
  • [1,10] digits
  • [0,1] special characters

I tried multiple approach, but without success. I don't know if I can do this verify with regex. The most accurate pattern is : ^(?=(.*[a-zA-Z]){1,6})(?=(.*[0-9]){1,10})(?=(.*[!@#$%^&*()\-__ .]){0,1})

But it don't work good when I have more than 6 char, 10 digits or 1 special character.

Could anyone help me?

CodePudding user response:

I might not use a single regex pattern, but would instead use multiple checks. For example:

String password = "ABC123@";
int numChars = password.replaceAll("(?i)[^A-Z] ", "").length();
int numDigits = password.replaceAll("\\D ", "").length();
int numSpecial = password.replaceAll("[^!@#$%^&*()_ .-]", "").length();

if (numChars >=1 && numChars <= 6 && numDigits >= 1 && numDigits <= 10 &&
    numSpecial <= 1) {
    System.out.println("password is valid");
}
else {
    System.out.println("password is invalid");
}
  • Related