Validate that password doesn't contain 3+ consecutive characters from name

12,840

Solution 1

For your 1,2,3,4 case

^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\d]{8,}$

For your 5th case

public boolean isValid(final String userName,final String password)
{
    for(int i=0;(i+2)<userName.length();i++)
          if(password.indexof(userName.substring(i,i+2))!=-1)
                return false;
    return true;
}

Solution 2

The last point is not something you do with regex. Loop through the name and check against the password instead.

Regex is good at patterns, not parsing. One way or another you have to use a loop to go through the name.

Share:
12,840
Vivek
Author by

Vivek

Updated on July 16, 2022

Comments

  • Vivek
    Vivek almost 2 years

    I need to do this following password validation in Java

    • Must be at least 8 characters in length
    • Must contain at least 1 number
    • Must contain at least 1 upper case letter
    • Must contain at least 1 lower case letter
    • Cannot contain 3 or more consecutive characters from your full name or your username (e.g. If your name is Will you couldn't have the password Stiller458)

    I have the first 4 points, how do I do the last one?

    Currently I have:

    String pattern = "^(?=.*[^a-zA-Z])(?=.*[a-z])(?=.*[A-Z])\\S{8,}$";
    boolean passwordValidation = originalPassword.matches(pattern);
    
  • Vivek
    Vivek almost 11 years
    I am getting an "java.lang.StringIndexOutOfBoundsException: String index out of range: 8", any idea why?
  • Anirudha
    Anirudha almost 11 years
    @Vivek oops..check out the edit now..instead of using userName.length() i used password.length()..small error
  • Vivek
    Vivek almost 11 years
    Tnx, also I changed if(password.indexof(userName.substring(i,i+2))!=-1) to if(password.indexOf(userName.substring(i,i+3))!=-1) to cater to contains 3 or more
  • Anirudha
    Anirudha almost 11 years
    @Vivek checking for 3 is as good as checking for 4,5,6,7,.... so you only need to check for 3 characters..