Java Regex Password Validation Example

Password validation is the need of almost all the applications today. There are various ways to do validate passwords from writing everything manually to use third party available APIs. In this Java regex password validation tutorial, We are building password validator using regular expressions.

1. Regex for password validation

((?=.*[a-z])(?=.*d)(?=.*[@#$%])(?=.*[A-Z]).{6,16})

Above regular expression has following sections:

(?=.*[a-z])     : This matches the presence of at least one lowercase letter.
(?=.*d)         : This matches the presence of at least one digit i.e. 0-9.
(?=.*[@#$%]) 	: This matches the presence of at least one special character.
((?=.*[A-Z])    : This matches the presence of at least one capital letter.
{6,16}          : This limits the length of password from minimum 6 letters to maximum 16 letters.

Ordering of top 4 sections can be changed or they can even dropped out from final regular expression. This fact can be used to build our password validator programmatically.

2. Java program to validate password using regex

We are making the our validator configurable so that one can put the limits based on needs. Like if we want to force at least one special character, but not any capital letter, we can pass the required arguments accordingly.

package com.howtodoinjava.regex;

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

public class PasswordValidator
{
	private static PasswordValidator INSTANCE = new PasswordValidator();
	private static String pattern = null;

	/**
	 * No one can make a direct instance
	 * */
	private PasswordValidator()
	{
		//do nothing
	}

	/**
	 * Force the user to build a validator using this way only
	 * */
	public static PasswordValidator buildValidator( boolean forceSpecialChar,
													boolean forceCapitalLetter,
													boolean forceNumber,
													int minLength,
													int maxLength)
	{
		StringBuilder patternBuilder = new StringBuilder("((?=.*[a-z])");

		if (forceSpecialChar)
		{
			patternBuilder.append("(?=.*[@#$%])");
		}

		if (forceCapitalLetter)
		{
			patternBuilder.append("(?=.*[A-Z])");
		}

		if (forceNumber)
		{
			patternBuilder.append("(?=.*d)");
		}

		patternBuilder.append(".{" + minLength + "," + maxLength + "})");
		pattern = patternBuilder.toString();

		return INSTANCE;
	}

	/**
	 * Here we will validate the password
	 * */
	public static boolean validatePassword(final String password)
	{
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(password);
		return m.matches();
	}
}

3. Unit test password validation

So our password validator is ready. Lets test it with some JUnit test cases.

package com.howtodoinjava.regex;

import junit.framework.Assert;

import org.junit.Test;

@SuppressWarnings("static-access")
public class TestPasswordValidator
{
	@Test
	public void testNormalPassword()
	{
		PasswordValidator validator = PasswordValidator.buildValidator(false, false, false, 6, 14);

		Assert.assertTrue(validator.validatePassword("howtodoinjava"));
		Assert.assertTrue(validator.validatePassword("howtodoin"));
		//Sort on length
		Assert.assertFalse(validator.validatePassword("howto"));
	}

	@Test
	public void testForceNumeric()
	{
		PasswordValidator validator = PasswordValidator.buildValidator(false,false, true, 6, 16);
		//Contains numeric
		Assert.assertTrue(validator.validatePassword("howtodoinjava12"));
		Assert.assertTrue(validator.validatePassword("34howtodoinjava"));
		Assert.assertTrue(validator.validatePassword("howtodo56injava"));
		//No numeric
		Assert.assertFalse(validator.validatePassword("howtodoinjava"));
	}

	@Test
	public void testForceCapitalLetter()
	{
		PasswordValidator validator = PasswordValidator.buildValidator(false,true, false, 6, 16);
		//Contains capitals
		Assert.assertTrue(validator.validatePassword("howtodoinjavA"));
		Assert.assertTrue(validator.validatePassword("Howtodoinjava"));
		Assert.assertTrue(validator.validatePassword("howtodOInjava"));
		//No capital letter
		Assert.assertFalse(validator.validatePassword("howtodoinjava"));
	}

	@Test
	public void testForceSpecialCharacter()
	{
		PasswordValidator validator = PasswordValidator.buildValidator(true,false, false, 6, 16);
		//Contains special char
		Assert.assertTrue(validator.validatePassword("howtod@injava"));
		Assert.assertTrue(validator.validatePassword("@Howtodoinjava"));
		Assert.assertTrue(validator.validatePassword("howtodOInjava@"));
		//No special char
		Assert.assertFalse(validator.validatePassword("howtodoinjava"));
	}
}

In this post we learned about password validation using Java regular expression, which is capable of validating alphanumeric and special characters, including maximun and minimum password length.

Happy Learning !!

Leave a Reply

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.