Password Strength Meter
25 July 2007Making a password strength meter is simple, there's no tricky Javascript or AJAX needed, just a simple function and a few divs.
I've decided to design the function around a scoring system, the stronger the password the higher the score. We can accomplish this with just a few simple IF statements.
function passwordStrength(pass)
{
var score = 0;
if(pass.length > 2)
score++;
if(pass.length > 4)
score++;
if(pass.length > 8)
score += 2;
if(/w/.test(pass) && /d/.test(pass))
score++;
return score * 2 * 10;
}The code is fairly self explanatory, the last IF statement checks if the password contains both characters and symbols. The function returns a percentage of the password's score out of 5, which is the maximum score it can be awarded.
Next, we need a form with a text box and 2 divs for our meter.
<input type="text" onkeyup="document.getElementById('passmeter').style.width = passwordStrength(this.value) + '%';" />
<br />
Password Strength:<br />
<div id="passmeterbg"><div id="passmeter"></div></div>
The 'onkeyup' event calls the passwordStrength() function every time a key is pressed. The 'width' property of our meter div is then given the password's score.
Finally, we need some CSS to style the meter...
#passmeter {
width: 0px;
background: #629d48;
height: 3px;
}
#passmeterbg {
height: 3px;
background: #f1f1f1;
width: 200px;
}
