1

I am trying to create a Regular Expression for password validation. Here are the requirements.

  1. Minimum length 8.
  2. At least 1 upper case.
  3. At least 1 lower case.
  4. At least 1 number.
  5. 0 or more of these characters !@#$%^&*?_~()- allowed.
  6. a-z allowed.
  7. A-Z allowed.
  8. 0-9 allowed.

Here is the expression i have so far:

^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*?_~()-]*).*$

This expression works mostly, except i need it to only allow bullets 5-9. Right now it will allow characters that are not specified, for example +=.

How can i modify this expression to only allow bullets 5-9 and no other characters?

prolink007
  • 33,872
  • 24
  • 117
  • 185

2 Answers2

2

You don't need lookahead-checks for the first and for the fifth to eigth condition - you can check this all in the final match, like

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\w!@#$%^&*?~()-]{8,}$

Using your lookahead checks for conditions 2-4. For the actual match we need at least 8 characters of your allowed characters. I have used \w intead of a-zA-Z0-9_ to keep things a bit shorter.

You can see it working here.

Site note: Restricting characters in passwords is usually seen as a bad idea. Also xkcd has something to say about passwords.

Sebastian Proske
  • 8,255
  • 2
  • 28
  • 37
1

You can break the RegExp into discrete portions, add or remove required portion, use Array.prototype.every(), include && !/[+=]/.test(str) within function, and .length property of input string

var matches = [/[A-Z]/, /[a-z]/, /\d/, /[!@#$%^&*?_~()-]/];
var str = "Ab0!#?~_";
var pw = matches.every(function(re) {
  return re.test(str) && !/[+=]/.test(str)
}) && str.length === 8;
console.log(pw);
guest271314
  • 1
  • 15
  • 104
  • 177