0

I took an online JavaScript test where the 3rd problem was as follows:

Complete the checkPassword function, which should check if the password parameter adheres to the following rules:

  • Must be longer than 6 characters.
  • Allowed characters are lower or uppercase Latin alphabetic characters (a-z), numbers (0-9), and special characters +, $, #, \, / only.
  • Must not have 3 or more consecutive numbers (e.g. "pass12p" is fine, but "pass125p" is not, because it contains "125")

>

My solution was as follows:

function checkPassword(password) {
  return /^[a-zA-Z0-9\+\$\\\/#]{6,}$/.test(password) && !/[0-9]{3,}/.test(password);
}

This solution gave me the correct outputs for the given inputs.

But the ultimate test result told that the solution is just 75% correct sadly.

I think the perfect answer is expected to be a solution just with a single regular expression. Is there anyone who can give me a single regular expression that gives the same result? I am not so good at regular expression so please advise.

I appreciate your help in advance.

Microtribute
  • 962
  • 10
  • 24
  • Welcome to SO! Please do search the site before asking a question - this exact one has been already answered. – georg Feb 14 '15 at 17:23

2 Answers2

3

Just use a negative lookahead at the start.

^(?!.*?\d{3})[a-zA-Z0-9\+\$\\\/#]{6,}$

(?!.*?\d{3}) at the start asserts that the match won't contain atleast three consecutive digits. Then the regex engine tries to match the pattern [a-zA-Z0-9\+\$\\\/#] against the input string 6 or more times only if this condition is satisfied.

DEMO

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0
 ^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\d]{6,}$

For consecutive number check

    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; 
}
Fahim
  • 12,198
  • 5
  • 39
  • 57