Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Password validation in Java using RegEx

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Could anyone help me?

>Solution :

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");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading