0

I'm looking into using a jQuery password strength indicator and have found one that looks suitable.

It increases the password strength score if special characters are detected:

if (password.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)){ score += 5 ;}

However I'd like to be able to specify additional special characters and because these lists of special characters are used in several places, I'd like to only specify the list once:

list = array(!,@,#,$,%,^,&,*,?,_,~,[,],{,},(,));
if (password.match(/(.*[list].*[list])/)){ score += 5 ;}

Is this possible?

2
  • stackoverflow.com/questions/11596556/… Commented Jul 11, 2013 at 9:01
  • Don't see any usage of jQuery here. Of course you can define list somewhere in global. Use list.join("") to get serialized chars list. Commented Jul 11, 2013 at 9:01

4 Answers 4

3

You can use strings:

var special = "!@#$%^&*?_~[]{}()".split('').join('\\');
if (password.match(new RegExp("(.*[" + special + "].*[" + special + "])")))...

(The join-with-backslashes escapes the special characters so they are treated literally by the regex engine.)

Sign up to request clarification or add additional context in comments.

Comments

2

Yes, if you use the RegExp() constructor, you can pass in a string as regexp.

var list = ['\\!', '\\@', '\\#', '\\%'];
var reg = new RegExp('(.*['+ list.join(',') + '].*['+ list.join(',') +'])');
if (reg.test("MySuperPassword!#_123")) {
    score += 5;
}

Comments

0

You do not need to separate chars by , in regex:

var list = "[\\!@#\\$%\\^&\\*\\?_~]";
var your_regex = new RegExp(".*" + list + ".*" + list);
if (your_regex.test(password)){
  score += 5;
}

3 Comments

you should also escape meaningful symbols, such as ? ... e.g. /[\?\!]/
you also can't embed variables in strings like "list" in JS, they need to be concatenated. Sorry, I guess I'm that guy
@Tim: there's no need to escape ? or ! here.
0

Why would you need a regex?

var list  = ['!','@','#','$','%','^','&','*','?','_','~','[',']','{','}','(',')'],
    score = 0;

for (var i=list.length;i--;) {
    if ( password.indexOf(list[i]) ) score++;
}

FIDDLE

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.