Implementation
This code snippet will return a score for the password strength.
It's pure Javascript so it should work for virtually every platform
and browser out there, even some mobile phones.
function CheckPassword(password)
{
var strength = new Array();
strength[0] = "Blank";
strength[1] = "Very Weak";
strength[2] = "Weak";
strength[3] = "Medium";
strength[4] = "Strong";
strength[5] = "Very Strong";
var score = 1;
if (password.length < 1)
return strength[0];
if (password.length < 4)
return strength[1];
if (password.length >= 8)
score++;
if (password.length >= 10)
score++;
if (password.match(/\d+/))
score++;
if (password.match(/[a-z]/) &&
password.match(/[A-Z]/))
score++;
if (password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,£,(,)]/))
score++;
return strength[score];
}
Usage
Call the function CheckPassword() passing the password
to be checked. The result is a string representing the password strength,
from "Very Weak" to "Very Strong". You can show this text in a label
and also block the form if the password strength is not strong or at least
medium.
You can also return the score (from 1 to 5) instead of the text, using
return score instead of return strength[score].
Example
<script type="text/javascript">
function PasswordChanged(field)
{
var span = document.getElementById("PasswordStrength");
span.innerHTML = CheckPassword(field.value);
}
function ButtonClicked(field)
{
var strength = document.getElementById("PasswordStrength").innerHTML;
if (strength.indexOf("Strong") < 0)
{
alert("Password is not strong enough!");
return false;
}
}
</script>
<div>
Password:
<input type="text" onchange="PasswordChanged(this)" />
<span id="PasswordStrength"></span>
<br />
<input type="button" value="Check" onclick="return ButtonClicked()" />
</div>
Our scripts will test passwords and return a score which represents its strength.
The score goes from 1 (Very Weak) to 5 (Very Strong),
and 0 if the value is blank. It will increase by 1 point if:
Note that if the password length is less than 4, the score will be
limited to "Very Weak".