Check Password Strength with JavaScript and Regular Expressions

Tonight I was doing some research on finding a good example of a Password Strength checker that uses JavaScript and Regular Expressions. In the application at my work, we do a post back to verify the password strength and it’s quite inconvenient for our users.

I found one example of some great Regular Expressions that look for a combination of length, characters and symbols, but the code was a little excessive for my taste and tailored for .NET. So I simplified the code.

Here’s the code. The Regular Expressions do a fantastic job of minimizing the length of the code:

<script language="javascript">
function passwordChanged() {
var strength = document.getElementById(‘strength’);
var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
var enoughRegex = new RegExp("(?=.{6,}).*", "g");
var pwd = document.getElementById("password");
if (pwd.value.length==0) {
strength.innerHTML = ‘Type Password’;
} else if (false == enoughRegex.test(pwd.value)) {
strength.innerHTML = ‘More Characters’;
} else if (strongRegex.test(pwd.value)) {
strength.innerHTML = ‘<span style="color:green">Strong!</span>’;
} else if (mediumRegex.test(pwd.value)) {
strength.innerHTML = ‘<span style="color:orange">Medium!</span>’;
} else {
strength.innerHTML = ‘<span style="color:red">Weak!</span>’;
}
}
</script>
<input name="password" id="password" type="text" size="15" maxlength="20" onkeyup="return passwordChanged();" />
<span id="strength">Type Password</span>

Thanks to Andrew Cain for getting me started!