Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
73
rated 0 times [  75] [ 2]  / answers: 1 / hits: 38714  / 13 Years ago, mon, november 21, 2011, 12:00:00

I want to create a function that compares a password against some commonly idiotic ones, so that the user can't pick one of these, but the function I have written so far, when put between script tags, causes no javascript to be recognized (by Firebug). I assume the array creation is at fault.



function unacceptable(pwd){
var unforgivable = [
/password/gi, /*g matches any occurance of sequence, i checks case insensitive*/
/12345678/g,
/8675309/g,
/[a-z]{8,}/gi,
/qwerty/gi,
/asdfg/gi,
/qazwsx/gi,
/zxcvb/gi,
/letmein/gi,
/trustno1/gi,
/omnicloud/gi,
/monkey/gi];
for (var i=0; i<unforgivable.length; i++)
if(pwd.match(unforgivable[i])) return true;
return false;
}

More From » regex

 Answers
10

You don't need the loop to test every word as you can put them all into one regular expression (separated by the | character) and let the regex engine look for any of them all at once. You could do that like this:



function unacceptable(pwd){
var unforgivable = [
password,
12345678,
8675309,
[a-z]{8,},
qwerty,
asdfg,
qazwsx,
zxcvb,
letmein,
trustno1,
omnicloud,
monkey
];
var re = new RegExp(unforgivable.join(|), i);
return re.test(pwd);
}


Working demo here: http://jsfiddle.net/jfriend00/cyVbC/



P.S. You don't have to put all the words into an array. You could just predeclare the entire regex, but I thought putting them in the array like this made for more readable code that was easier to maintain.



It could also be this:



var unforgivable = /password|12345678|8675309|[a-z]{8,}|qwerty|asdfg|qazwsx|zxcvb|letmein|trustno1|omnicloud|monkey/i;

function unacceptable(pwd){
return unforgivable.test(pwd);
}

[#88996] Friday, November 18, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryder

Total Points: 473
Total Questions: 110
Total Answers: 91

Location: Northern Ireland
Member since Mon, Nov 14, 2022
2 Years ago
;