Home » Core Java » util » regex » Matcher » Validate Password with Java Regular Expression example

About Nikos Maravitsas

Nikos Maravitsas
Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

Validate Password with Java Regular Expression example

In the previous tutorial on username validation we explained why input validation is important for your application’s security and data consistency.

For our passwords we are going to implement a strict policy about their format. We want our passwords to :

  • Be between 8 and 40 characters long
  • Contain at least one digit.
  • Contain at least one lower case character.
  • Contain at least one upper case character.
  • Contain at least on special character from [ @ # $ % ! . ].

So this is the regular expression we are going to use for password validation:


You can take a look at the Pattern class documentation to learn how to construct your own regular expressions according to your policy.

1. Validator class

This is the class that we are going to use for password validation.


package com.javacodegeeks.java.core;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PasswordValidator {

	private Pattern pattern;
	private Matcher matcher;

	private static final String PASSWORD_PATTERN = "((?=.*[a-z])(?=.*\\d)(?=.*[A-Z])(?=.*[@#$%!]).{8,40})";

	public PasswordValidator() {
		pattern = Pattern.compile(PASSWORD_PATTERN);

	public boolean validate(final String password) {

		matcher = pattern.matcher(password);
		return matcher.matches();


2. Unit Testing our PasswordValidator class

For unit testing we are going to use JUnit. Unit testing is very important in these situations because they provide good feedback about the correctness of our regular expressions. You can test your program and reassure that your regular expression meets the rules on your policy about the form of the usernames or passwords. For example, you might have a black list of usernames or passwords that you don’t want to have to your system, You cant test your validator against these values to see how it responds.

This is a basic test class:


package com.javacodegeeks.java.core;

import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.Collection;

import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

public class PasswordValidatorTest {

	private String arg;
	private static PasswordValidator passwordValidator;
	private Boolean expectedValidation;

	public PasswordValidatorTest(String str, Boolean expectedValidation) {
		this.arg = str;
		this.expectedValidation = expectedValidation;

	public static void initialize() {
		passwordValidator = new PasswordValidator();

	public static Collection<Object[]> data() {
		Object[][] data = new Object[][] {
				{"n!k@s",false },                         // it's less that 8 characters long 
				{ "gregorymarjames-law", false },         // it doesn't contain an digits or upper case characters
				{ " abcdFg45*", false },                  // characters ~ in not allowed     
				{ "n!koabcD#AX", false },                 // there should be a digit  
				{ "ABCASWF2!", false   },                 // there should be a lower case character

				// valid passwords

				{"n!k@sn1Kos",true },                         
				{ "J@vaC0deG##ks", true },         
				{ "n!k1abcD#!", true } };

		return Arrays.asList(data);

	public void test() {
		Boolean res = passwordValidator.validate(this.arg);
		String validv = (res) ? "valid" : "invalid";
		System.out.println("Password "+arg+ " is " + validv);
		assertEquals("Result", this.expectedValidation, res);




Password n!k@s is invalid
Password gregorymarjames-law is invalid
Password  abcdFg45* is invalid
Password n!koabcD#AX is invalid
Password ABCASWF2! is invalid
Password n!k@sn1Kos is valid
Password J@vaC0deG##ks is valid
Password n!k1abcD#! is valid

This was an example on how to validate password with Java Regular Expression.

(No Ratings Yet)
1 Comment Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area


Leave a Reply

1 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
Annonymous Recent comment authors
newest oldest most voted
Notify of

n!k@sn1Kos~~ input will also give true for this regex though ~ is not allowed.