Java Regex Password Validation Example

Password validation is the need of almost all applications today. There are various ways to validate passwords from writing everything manually to using third-party available APIs. In this password validation tutorial, we are building a password validator using regular expressions. 1. Regex for Validating the Passwords ((?=.*[a-z])(?=.*d)(?=.*[@#$%])(?=.*[A-Z]).{6,16}) The …

Java regex

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

1. Regex for Validating the Passwords

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

The above regular expression has the 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.

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

2. Java program to validate passwords using regex

We are making 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.

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 Tests for Password Validation

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

@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 maximum and minimum password length.

Happy Learning !!

Comments

Subscribe
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.