Password Strength Check Function
Login or Register to Bookmark this snippet
This function returns an associative array of values determining the strength of str. It can also determine if the password is the same as the user name, uname.
Usage:
var strength = passwordStrength('walter','user566');
Then use the variable like:
alert(strength.text);
Along with text, you also have strength and error attributes.
function passwordStrength(str, uname) {
if (!str || typeof(str) == 'undefined' || str.length < 8) {
return {strength: 0, error: 1, text:'The password is not long enough'};
} else {
var length = str.length;
//check for a couple of bad passwords:
if (uname && str.toLowerCase() == uname.toLowerCase()) {
return{strength: 0, error:4, text:'Password cannot be the same as your Username'};
}
if (str.toLowerCase() == 'password') {
return {strength: 0, error: 3, text:'Password is too common'};
}
//see if there are 3 consecutive chars (or more) and fail!
var consecutives = str.match(/(.)1{2}/g);
if (consecutives) {
return {strength: 0, error: 2, text:'Too many consecutive characters'};
}
//count the number of numerics
var numbers = str.match(/d/g);
if (numbers) {
numbers = numbers.length
} else {
var numbers = 0;
}
//count the number of uppercase chars
var uppers = str.match(/[A-Z]/g);
if (uppers) {
uppers = uppers.length
} else {
var uppers = 0;
}
//count the number of non-alhpa-num chars
var others = str.match(/[^A-z0-9]/g);
if (others) {
others = others.length
} else {
var others = 0;
}
//and weigh them all up.
if (others > 1 || (uppers > 1 && numbers > 1)) {
//bulletproof
return {strength: 5, error: 0, text:'Virtually Bulletproof'};
} else if ((uppers > 0 && numbers > 0) || length > 14) {
//very strong
return {strength: 4, error: 0, text:'Very Strong'};
} else if (uppers > 0 || numbers > 2 || length > 9) {
//strong
return {strength: 3, error: 0, text:'Strong'};
} else if (numbers > 1) {
//good
return {strength: 2, error: 0, text:'Fair'};
}
//fair
return {strength: 1, error: 0, text:'Weak'};
}
}
Added by JC on 18th December, 2007
There are no comments about this snippet.
You must be registered and logged in to post a comment.
Login here to post a comment