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, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
vince
Guest
vince

need password 8-20 charactors one uppercase one number thanks

Amil Amilov
Guest
Amil Amilov

need help to set Password

Anand
Guest
Anand

Hi please give the regrex for.

Password comprises of alphabets [upper case(A-Z), lower case(a-z)] and/or numeral (0-9) and at least one ASCII special character

Thanks in advance!

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

Manoj Sawant
Guest
Manoj Sawant

You can do that using Char Code with/without JavaScript.

-1) Take char code of each key pressed by user and store it in array,

-2) You can apply your logic on that array. like if array contains sequential char code for each key then return false.

Example:- For input “123456789” you will get char code array as [49, 50, 51, 52, 53, 54, 55, 56, 57] then you can find difference between (N) th & (N+1) st element and return false if difference is one.

This can be useful for “12345678”, “abcdef”, “zyxwvuts”, 0987654321,

Soumen
Guest
Soumen

Is it possible to find the sequential character through regex?

Marie
Guest
Marie

Thank you very much. Pretty helpful!

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})

OtaTat
Guest
OtaTat

Try this one

 (?=.*[A-Z])(?=.*[a-z])(?=.*\\d)(?!.*\\s)(?=.*[._/-])[a-zA-Z].{8,23} 
Abhigyan Ghosh
Guest
Abhigyan Ghosh

It accepts mkyoNg123*% though. How to fix it?

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

HARENDRA KUMAR
Guest
HARENDRA KUMAR

CBSCNEET

Cristian
Guest
Cristian

Why does the regex automatically become false if you remove the length count .{6,20}??

Sindee
Guest
Sindee

That goes to show that the images on guides should be straightforward to relate with as well as identify. In enhancement, stick to books that have easy coloring pages, which have well-spaced pictures for example coloring and ensure you have enough pastel and also coloring pencils to for all. You could have two children on a book each taking a turn to color an image. It is an excellent means of educating them the values of sharing.

Zohar Leroy
Guest
Zohar Leroy

Some things I did not understand , I got the Class “PassValidator”
how do I use it xD

Paul Taylor
Guest
Paul Taylor

The regex doesn’t enforce all characters in the string. Once the threshold is met then any other characters are allowed (before or after the minimum) including special characters for databases, Javascript, browsers, etc.

Example that works (note, this web site form may remove the less than and greater than tags):
alert(“hacked”)ThisRegExDoesNotWorkAsAdvertisedthisIS@2479889

hemalait
Guest
hemalait

I really like your way of explaining things. Thanks !

lak
Guest
lak

I notices some wired thing going in here. After I enter the min required length of passowrd it allowing me to enter any special character in there,

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

I entered the Test123$*()>< after 6 letters I can enter whatever the character I want. How should we fix it.

http://www.rubular.com/r/UAwoaPM0Ji

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.

Cristian
Guest
Cristian

I stumpled upon your comment and thought i would give my solution to this, which is probably not the best but works.
# Convert the string to a char array
# With for loop match the indexes if(char[a] == char[a+1])
# ‘silent swallow’ IndexOutOfBoundsException
# if repeating characters are more than X, password = bad

jagadeesh kumar
Guest
jagadeesh kumar

its allowing {}()_- values also

Zeynep Onur
Guest
Zeynep Onur

Thank you for this post, very well. I need help, can you describe it?
/w + ( [- + . ‘] /w +) * @ /w + ( [ – . ] /w+) * /./w + ( [- . ] /w + )*

Deb
Guest
Deb

Hi mkyong, Thank you for this Tutorial.

I have a requirement to 1. Allow at least i numeric 2. one alplabet 3. Dont allow any special character or space. I have the expression as PATTERN = “((?=.*\d)(?=.*[a-zA-Z][^@#$%.//])(?=\S+$).{8,20})”;
However this is allowing ‘.’ char.
surprisingly it is allowing ‘AB.CD1a11’ and restricting ‘a.111111111A’.

Appreciate any help in this issue.

Maqsood
Guest
Maqsood

Nice RegEx

Sawyer
Guest
Sawyer

Thanks so much for this. Any help about how to modify your regex to check for a number OR symbol? I thought (?=.*[0-9]|[!@#$%] might work, but no luck. Also, as someone else mentioned, it seems to be accepting spaces. How can I make it fail if the user enters spaces? Thanks!

Hi
Guest
Hi

Thanks

Brice Vandeputte
Guest
Brice Vandeputte

5 years after, this post is always usefull (as the rest of you blog ;))
just another way here to say thanks again Mkyong to save our time ^^

Rahul
Guest
Rahul

how to do this for JPasswordField Component

henry
Guest
henry

i am learning regex through various website but did not see “?=” explanation. though read “?:” – matches w/o remembering matched text,”?>” matches w/o backtracking and etc. Would someone explain what “?=” does here ?

Manoj Sawant
Guest
Manoj Sawant

“?=” means POSITIVE LOOKAHEAD which matches a group after the main expression without including it in the result.

As MKYONG explained :

?= – means apply the assertion condition,
?= is meaningless by itself (without including itself in the result),
?= always work with other combination.

that’s why “?=” used inside brackets like (?=.*[a-z]) in this example.

Aman raj
Guest
Aman raj

How about the fact that passwords should never ever be stored/converted in Strings due to security reasons?? I think that’s why java implements storing the password in char array rather than strings.

V?n Ch??ng Nguy?n
Guest
V?n Ch??ng Nguy?n

Hi,
?= – means apply the assertion condition, meaningless by itself, always work with other combination
I have not really understood. could you clearly explain that for me ?
Many Thanks

Manoj Sawant
Guest
Manoj Sawant

“?=” means POSITIVE LOOKAHEAD which matches a group after the main expression without including it in the result.

As MKYONG explained :

?= – means apply the assertion condition,
?= is meaningless by itself (without including itself in the result),
?= always work with other combination.

that’s why “?=” used inside brackets like (?=.*[a-z]) in this example.

Jorge Rivera
Guest
Jorge Rivera

Why in the world would anyone want to limit maximum password length?

Manoj Sawant
Guest
Manoj Sawant
As every one try to make password which is difficult to get read / understand / remember by other. If any user making very long and complicated password then, in future he/she also will not able to remember that. And if someone uses long password for Online Bank Transactions or any Online Reservation System then, may be he/she could try to insert password with all attempts. Due to which he could not get success in his transaction. And Software Developer have to make system user friendly. Developers need to take care of network traffic also. It’s not good thing If… Read more »
Jorge Rivera
Guest
Jorge Rivera

security is more important than an user making 3 to 4 requests and things like that. I have never seen a security expert recommending to limit the length of the password but I have read many times why you as a developer should never set an artificial limit on the password length.

Christopher
Guest
Christopher

I would think it is more so you can allocate dedicated space for a password array of min 8 and no more then 20 char. Regardless of the user ability to remember the password the memory space it would take for users to enter what ever they wanted would be inefficient. This way you can establish a clean uniform array of dedicate value.

Jorge Rivera
Guest
Jorge Rivera

This is only an issue if you are saving the password as plain text since a hash function will always have a fixed length string as a result.

Maycon
Guest
Maycon

this allow any caractere,except space, and it must to contain a letter and a number:

^\S*(?=\S*[a-zA-Z])(?=\S*[0-9])\S*$

seded
Guest
seded

to escape the . and , from the regex

ih
Guest
ih

dffbdf

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,