Check Password Strength with JavaScript and Regular Expressions
Happy New Year! Marketing Technology finds and reports on the latest technology that will enable your business to effectively market to your audience, for acquisition or retention strategies. Subscribe now the Marketing Technology Blog RSS feed or to the Marketing Technology Email to have new content sent directly to your inbox. You'll also find my other business blog helpful, Social Media Domination.
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 and here’s a demonstration (if you’d like the code, simply right-click the link and save as):
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!



I love you, too!
Had same experience as Janis.
This works right out of the box which is perfect for people like me who cant code javascript!
instead of tag,and it didn’t work,any suggestions?!
Thanks Douglas, I use it for my current job.
To deploy such a feature on a professionnal solution, I believe it is important to combine this algorithm with a dictionnary check.