This post covers various methods to validate a password in Java.

We have seen that a character array is preferred over a String object for storing highly sensitive information such as user passwords in Java. But if you must use a string to store a password, then you can use any of the following methods to validate it:

1. Using OWASP Validator

We can use OWASP Validation Regex, which is considered to be very safe. The regular expression requires the password to have 4 to 8 characters and should contain numbers, lowercase and uppercase letters.

^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{4,8}$

Following is the breakdown of each component:

^               # start of the string
(?=.*\d)        # a digit must occur at least once
(?=.*[a-z])     # a lower case letter must occur at least once
(?=.*[A-Z])     # an upper case letter must occur at least once
.{4,8}          # 4-8 character password, both inclusive
$               # end of the string

 
Here’s the complex version, which requires a password to have 4 to 32 characters. The password should satisfy at least 3 out of 4 conditions (uppercase and lowercase letters, numbers, and special characters) and should not have more than 2 equal characters in a row.

^(?:(?=.*\d)(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[^A-Za-z0-9])(?=.*[a-z])|(?=.*[^A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9]))(?!.*(.)\1{2,})[A-Za-z0-9!~<>,;:_=?*+#.”&§%°()\|\[\]\-\$\^\@\/]{8,32}$

Download  Run Code

Output:

The Password Stream@Java8 is valid

2. Using Another Regular Expression

Here’s another regular expression for validating a password, taken from the Stack Overflow thread. This is basically an extension of OWASP Regex seen before. Since every rule is an independent “module”, we can easily add, modify, or remove individual rules.

^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,}$

Following is the detailed explanation:

^                  # start of the string
(?=.*[0-9])        # a digit must occur at least once
(?=.*[a-z])        # a lower case letter must occur at least once
(?=.*[A-Z])        # an upper case letter must occur at least once
(?=.*[@#$%^&+=])   # a special character must occur at least once
(?=\\S+$)          # no whitespace allowed in the entire string
.{8,16}            # 8-16 character password, both inclusive
$                  # end of the string

Download  Run Code

Output:

The Password Java#@#8 is valid

That’s all about validating a password in Java.