Skip to content

Instantly share code, notes, and snippets.

@garakh
Forked from stgogm/password-strength.js
Created November 9, 2021 13:31
Show Gist options
  • Save garakh/6ec8c735748dffbe4bf407ebd51a7735 to your computer and use it in GitHub Desktop.
Save garakh/6ec8c735748dffbe4bf407ebd51a7735 to your computer and use it in GitHub Desktop.
/**
* Scores a password's strength.
*
* It scores a password according to several factors like character variation,
* repetition and length. The passwords are scored in a numeric point scale that
* varies from less than 0 to 100 and more. A safe password score should be
* considered as 49 points or more.
*
* @param {String} pwd The password string to score.
*
* @returns {Number} The password score.
*
* @see https://stackoverflow.com/questions/948172/password-strength-meter/11268104#11268104
*/
function scorePassword(pwd) {
var check, ltr, i, l;
var variation = 0;
var letters = {};
var score = 0;
if (!pwd) {
return score;
}
/* Score character variation */
var variations = {
lower: /[a-z]/.test(pwd),
upper: /[A-Z]/.test(pwd),
nonWords: /\W/.test(pwd),
digits: /\d/.test(pwd)
};
for (check in variations) {
variation += variations[check] ? 1 : 0;
}
score += (variation - 1) * 10;
/* Score unique letters until 5 repetitions */
for (i = 0, l = pwd.length; i < l; i++) {
ltr = letters[pwd[i]] = (letters[pwd[i]] || 0) + 1;
score += 5 / ltr;
}
/* Score length (about 8 chars for a safe password) */
score -= 16 - (pwd.length / 16);
return parseInt(score);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment