How to validate password with regular expression in java

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

Code :

package com.codewr.javacore.regular.expression;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

 

/**

 *

 * @author codewr

 */

public class PasswordValidator {

 

    /**

     *  (         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

     */

    private static final String PASSWORD_PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})";

 

    public static void main(String[] args) {

        PasswordValidator passwordValidator = new PasswordValidator();

        //check  password validate

        boolean isValid = passwordValidator.validate("codewr12");

        System.out.println("password valid is " + isValid);

    }

 

    /**

     * Validate password with regular expression

     *

     * @param password password for validation

     * @return true valid password, false invalid password

     */

    public boolean validate(final String password) {

        Pattern pattern = Pattern.compile(PASSWORD_PATTERN);

        Matcher matcher = pattern.matcher(password);

        return matcher.matches();

 

    }

}

 

Code UnitTest:

- [email protected], codeWR12$: valid password

- [email protected]: invalid because too short , min 6 characters

- [email protected]: invalid because uppercase characters is required

- codeWr12* : invalid because symbol “*” is not allow

- [email protected]: invalid because digit is required

- CODEWR12$: invalid because lowercase characters is required

- [email protected]:             invalid because too long, max 20 characters

import com.codewr.javacore.regular.expression.PasswordValidator;

import org.testng.Assert;

import org.testng.annotations.*;

 

/**

 * Password validator Testing

 * @author codewr

 *

 */

public class PasswordValidatorTest {

 

       private PasswordValidator passwordValidator;

 

       @BeforeClass

        public void initData(){

              passwordValidator = new PasswordValidator();

        }

 

       @DataProvider

       public Object[][] ValidPasswordProvider() {

              return new Object[][]{

                 {new String[] {

                        "[email protected]", "codeWR12$"

                 }}

               };

       }

      

       @DataProvider

       public Object[][] InvalidPasswordProvider() {

              return new Object[][]{

                 {new String[] {

                        "[email protected]","[email protected]","codeWr12*",

                            "[email protected]","CODEWR12$","[email protected]"

                 }}

              };

       }

      

       @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);

          }

       }

}

Output:

Running PasswordValidatorTest

Password is valid : [email protected] , true

Password is valid : codeWR12$ , true

Password is valid : [email protected] , false

Password is valid : [email protected] , false

Password is valid : codeWr12* , false

Password is valid : [email protected] , false

Password is valid : CODEWR12$ , false

Password is valid : [email protected] , false

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.406 sec

 

Results :

 

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

Note: file pom.xml add maven

<dependency>

<groupId>org.testng</groupId>

<artifactId>testng</artifactId>

<version>6.8</version>

<scope>test</scope>

</dependency>