HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java Regular Expressions / Java Regex Password Validation Example

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 !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. ASHOK NARMETA

    October 25, 2019

    when ever we validating its follwing same as regex pattern…

  2. Peter Jurkovic

    June 5, 2014

    Hi, you have an error in you regex at line 42, there should be patternBuilder.append("(?=.*\d)");

Comments are closed on this article!

Search Tutorials

Java Regex Tutorial

  • Java Regex – Introduction
  • Java Regex : Alphanumeric
  • Java Regex : Credit Card Numbers
  • Java Regex : Canadian Postcodes
  • Java Regex : Currency Symbol
  • Java Regex : Date Format
  • Java Regex : Email Address
  • Java Regex : Password
  • Java Regex : Greek Characters
  • Java Regex : ISBNs
  • Java Regex : Min/Max Length
  • Java Regex : No. of Lines
  • Java Regex : No. of Words
  • Java Regex : SSN
  • Java Regex : UK Postal Codes
  • Java Regex : US Postal Codes
  • Java Regex : Trademark Symbol
  • Java Regex : Intl Phone Numbers
  • North American Phone Numbers

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces