RegEx

Java Regular Expression Password Validation Example

Previously we covered how to validate username using regular expression in Java. Java Regular Expression Password Validation example shows how to validate password using Java regular expression. This pattern can be used to validate password requirements like alphanumeric characters, total length and special characters.

Java Regular Expression Password Validation

There may be different requirements for password validation. This example covers most common requirements of them. Example requirements are as follows.

1) Password must contain at least 8 characters
2) Password must contain at least 1 number
3) Password must contain at least 1 upper case letter
4) Password must contain at least 1 lower case letter
5) Password must contain at least 1 special character
6) Password must not contain any spaces

Let’s try to build the regular expression pattern for the above requirements one by one. Here is the initial pattern for the first two requirements.

Where,

Positive lookahead expression (?=.*[0-9]) will return true for any character followed by a digit (thus satisfying our requirement number 2). {8,} will satisfy requirement number 1 of minimum length.

Let’s try out our initial password regular expression pattern.

Output

As you may have observed, all the passwords containing a digit and minimum 8 in length turned out to be a valid password as per our pattern. “mypassword” is not a valid one because it does not contain a digit, while “F@rd1co” is not valid as it does not satisfy our minimum length requirement.

Let’s now try to implement requirements 3, 4, 5 and 6 in a same way as requirement 2. Basically, we want one positive lookahead expression per requirement as given below.

Where,

Let’s try the pattern.

Output

Explanation for failed password test cases:

You may have observed that our last test case “<RRPhantom@16>” turned out to be a valid password even though we did not have “<” and “>” in our special characters list. It is because once any special character out of the allowed characters is found in the string (in this case “@”), lookahead expression does not check for others and returns true.

While this is not a problem in most cases, but if you have the requirement for password to contain only special characters from the predefined set of characters, you can change the pattern as follows.

We have added only one extra check in the above pattern “[a-zA-Z0-9!@#$%^&*]” which makes sure that password contains characters from predefined set of characters (i.e. all lower and upper case letters, 0 to 9 digits and special character out of “!@#$%^&*”characters. If password contains any character which is not in this list, pattern will fail and matches method will return false.

Output

Please let us know your views in the comments section below.

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

Tags