How to validate password with regular expression

Password Regular Expression Pattern


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

Description


(			# Start of group
  (?=.*\d)		#   must contains one digit from 0-9
  (?=.*[a-z])		#   must contains one lowercase characters
  (?=.*[A-Z])		#   must contains one uppercase characters
  (?=.*[@#$%])		#   must contains one special symbols in the list "@#$%"
              .		#     match anything with previous condition checking
                {6,20}	#        length at least 6 characters and maximum of 20	
)			# End of group

?= – means apply the assertion condition, meaningless by itself, always work with other combination

Whole combination is means, 6 to 20 characters string with at least one digit, one upper case letter, one lower case letter and one special symbol (“@#$%”). This regular expression pattern is very useful to implement a strong and complex password.

P.S The grouping formula order is doesn’t matter.

1. Java Regular Expression Example

PasswordValidator.java

package com.mkyong.regex;

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 = 
              "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})";
	        
	  public PasswordValidator(){
		  pattern = Pattern.compile(PASSWORD_PATTERN);
	  }
	  
	  /**
	   * Validate password with regular expression
	   * @param password password for validation
	   * @return true valid password, false invalid password
	   */
	  public boolean validate(final String password){
		  
		  matcher = pattern.matcher(password);
		  return matcher.matches();
	    	    
	  }
}

2. Password that match:

1. mkyong1A@
2. mkYOn12$

3. Password that doesn’t match:

1. mY1A@ , too short, minimum 6 characters
2. mkyong12@ , uppercase characters is required
3. mkyoNg12* , special symbol “*” is not allow here
4. mkyonG$$, digit is required
5. MKYONG12$ , lower case character is required

4. Unit Test – PasswordValidator

Unit test with TestNG.

PasswordValidatorTest.java

package com.mkyong.regex;

import org.testng.Assert;
import org.testng.annotations.*;
 
/**
 * Password validator Testing
 * @author mkyong
 *
 */
public class PasswordValidatorTest {
 
	private PasswordValidator passwordValidator;
    
	@BeforeClass
        public void initData(){
		passwordValidator = new PasswordValidator();
        }
    
	@DataProvider
	public Object[][] ValidPasswordProvider() {
		return new Object[][]{
		   {new String[] {
			   "mkyong1A@", "mkYOn12$", 
		   }}
	        };
	}
	
	@DataProvider
	public Object[][] InvalidPasswordProvider() {
		return new Object[][]{
		   {new String[] {
			   "mY1A@","mkyong12@","mkyoNg12*",
                            "mkyonG$$","MKYONG12$"	  
		   }}
	       };
	}
	
	@Test(dataProvider = "ValidPasswordProvider")
	public void ValidPasswordTest(String[] password) {
		
	   for(String temp : password){
		boolean valid = passwordValidator.validate(temp);
		System.out.println("Password is valid : " + temp + " , " + valid);
		Assert.assertEquals(true, valid);
	   }
	   
	}
	
	@Test(dataProvider = "InvalidPasswordProvider", 
                 dependsOnMethods="ValidPasswordTest")
	public void InValidPasswordTest(String[] password) {
		
	   for(String temp : password){
		boolean valid = passwordValidator.validate(temp);
		System.out.println("Password is valid : " + temp + " , " + valid);
		Assert.assertEquals(false, valid);
	   }
	}
}

5. Unit Test – Result


Password is valid : mkyong1A@ , true
Password is valid : mkYOn12$ , true
Password is valid : mY1A@ , false
Password is valid : mkyong12@ , false
Password is valid : mkyoNg12* , false
Password is valid : mkyonG$$ , false
Password is valid : MKYONG12$ , false
PASSED: ValidPasswordTest([Ljava.lang.String;@1d4c61c)
PASSED: InValidPasswordTest([Ljava.lang.String;@116471f)

===============================================
    com.mkyong.regex.PasswordValidatorTest
    Tests run: 2, Failures: 0, Skips: 0
===============================================


===============================================
mkyong
Total tests run: 2, Failures: 0, Skips: 0
===============================================

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
59 Comment threads
19 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
64 Comment authors
Anoop VShaik Samsuddinamit jajuRameshTravis Recent comment authors
newest oldest most voted
vince
Guest
vince

need password 8-20 charactors one uppercase one number thanks

trackback
10 Java Regular Expression Examples You Should Know | Regular Expressions

[…] ==> See the explanation and example here […]

rudresh
Guest
rudresh

Hi its works perfect but first letter should be in character, how to add that.

i tried adding like below in the beginning but its expecting again the capital or small letter; ex:

1) Rudresh.12s its return false; its expects Upper case letter again
2) rUDRESH.12s it return false; its expects Lower case letter again

^[a-zA-Z]((?=.*[A-Z])(?=.*[a-z])(?=.*\\d)(?!.*\\s)(?=.*[._/-]).{9,24})

Marie
Guest
Marie

Thank you very much. Pretty helpful!

Fernie
Guest
Fernie

Hi All,

What if password should not include easy-to-guess string such as “love”, “happy”, “12345678”, “qwerty”, “asdfgh”, “zxcvb”. How can regular expression validate such strings?

Regards,
Fernie

Leonidas
Guest
Leonidas

With this reg exp I could introduce the following password:

aaaaaaaaaaaaaaaaaaaa1A$

Yes, it’s good (because the length), but I think the password restrictions (I mean, one character of each group) can be avoided. Not too good.

hari
Guest
hari

Your password must satisfy the following:

Password must be 8 to 13 character long.
Password must have at least one Upper case alphabet.
Password must have at least one Lower case alphabet.
Password must have at least one numeric value.
Password must have at least one special characters eg.!@#$%^&*-

help me now

trackback
JSF 2 validateRegex example

[…] The above regex pattern is required 6 to 20 characters string with at least one digit, one upper case letter, one lower case letter and one special symbol (“@#$%”). This is strong and complex enough for a password validation, see this password validation with regular expression. […]

Alex
Guest
Alex

Good night,

I’m not able to pass parameters to the regular expression for example:
“((?=.*\\d{3})(?=.*[a-z]{5})(?=.*[A-Z]{2})(?=.*[@#$%]{2}).{4,20})”;
((?=.*\\d{3}) == Change de number 3 to a variable .

Thanks a lot,

Mo Fielding
Guest
Mo Fielding

Thanks! Very helpful. I slept through the regex stuff in class… 🙁

John
Guest
John

This regEx fails for April123
Why is that so?

According to pattern it should not pass right?

Jeremiah
Guest
Jeremiah

Using this string as test data: “X@CpJ[8~”

It would return true, even though the characters ‘[‘ and ‘~’ are not allowed.

trackback
Wicket password field example

[…] Validate password with regular expression […]

Belen Kotow
Guest
Belen Kotow

yeah, you are right. this is a very good articles.i have learned so many things from

Jonas Grimsgaard
Guest
Jonas Grimsgaard

Thank you, you saved me ALOT of time ?

chris k
Guest
chris k

Thanks for this! Saved me a lot of time. Much appreciated Mkyong!

Lincoln Baxter, III
Guest
Lincoln Baxter, III

Hey! Great example – I’d like to suggest a slight adaptation, however. While it is tempting to use a single regular expression for this, I think that there are good reasons to actually split up the regex into multiple checks. Performance is not usually a concern with password checking, so invoking a few more regex calls isn’t really a big deal, like so: http://ocpsoft.org/opensource/guide-to-regular-expressions-in-java-part-1/#comment-4097

trackback
Java Regular Expression Tutorial

[…] Password regular expression Password regular expression example in Java and unit tested with TestNG. ((?=.*d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20}) […]

Haider M Rizvi
Guest
Haider M Rizvi

This post helped me. Thanks.

Tomek
Guest
Tomek

3. mkyoNg12* , special symbol “*” is not allow here

true, but try this:
Ng1#**** – allowed!

(in fact there could be ANY char in place of ‘*’;

If you would like to limit chars to only [a-zA-Z0-9@#$%] use:

((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%])[a-zA-Z0-9@#$%]{6,20})

Raymond Ng
Guest
Raymond Ng

Add (?!.*\\s) to disallow spaces in the password.

shiva
Guest
shiva

it’s accepting space

Konrad
Guest
Konrad

I recommend: ((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})([a-zA-Z\@\#\$\%\d])
this will be block other marks

muneeb
Guest
muneeb

c program ask user to enter password of 6 character and check wether it is a strong password

Aniketh
Guest
Aniketh

Thanks ….. works great

Anonymous
Guest
Anonymous

Hi Mkyong.
what is the pattern for gmail passwords?
Cheers.

mrlami
Guest
mrlami

Dude… Awesome!

Anonymous
Guest
Anonymous

/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\d@#$%_-]{8,20}$/

required; min 1 lowercase letter, min 1 uppercase letter, @#$%_- special character accepting. disallow spaces, minlength 8 maxlength 20 character.

good luck.

raj
Guest
raj

hi,
i need regular expression for password validation which accepts only one character
(from a-z) and any number of digits where password size is 8 characters.
for ex:143h6434—> valid
143d432y—> invalid

in spring mvc

thanks in advance,

ih
Guest
ih

dffbdf