1

I want a function checkPassword function, which should check if the password parameter adheres to the following rules:

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

checkPassword should print "true" to the console if the password parameter adheres to the said rules, and "false" if it does not.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
ANJYR
  • 2,583
  • 6
  • 39
  • 60

3 Answers3

3

You can use the following regex and get the content of the capturing group to check if your string is valid:

.*\d{3}.*|^([\w\+$#/\\]{6,})$

Working demo

Using \w allows A-Za-z0-9_ if you don't want underscore on your regex you have to replace \w by A-Za-z0-9

For the following examples:

pass12p            --> Pass
pass125p           --> Won't pass
asdfasf12asdf34    --> Pass
asdfasf12345asdf34 --> Won't pass

Match information is:

MATCH 1
1.  `pass12p`
MATCH 2
1.  `asdfasf12asdf34`
Federico Piazza
  • 30,085
  • 15
  • 87
  • 123
0

The best way would be to use two separate regular expressions. First, make sure the password matches this first one, which checks for adherence to rules #1 and #2:

[A-Za-z0-9#$\/\\\+]{6,}

Then, make sure the password does not match this second regular expression, which checks for the presence of a sequence of 3 consecutive numbers anywhere in the password:

\d{3}
theftprevention
  • 5,083
  • 3
  • 18
  • 31
-1
function checkPassword(str) {
  console.log( /^(?!.*\d{3})[+a-z\d$#\\/]{6,}$/i.test(str) );
}
MikeM
  • 13,156
  • 2
  • 34
  • 47