Forum Moderators: open
Using the test code below, type the following string, "teSt" (without the quotation marks) then press the Shift key 5 times and the "strength" level will fluctuate from 1 to 2 (Fair to Weak) as you repeatedly press the Shift key.
I'm flabbergasted as the depressing of the shift key should not be changing the .value of the field!
I'm not sure how to go about fixing this... isn't there some way to cancel the function if it's called from an onkeyup of the shift key? Any help is appreciated! :)
Complete code:
<style type="text/css">
<!--
div#strengthmeter { width: 300px; height: 20px; }
div#strengthmeter div { width: 200px; height: 20px; background: #ccc; float: left; }
div#strengthmeter div #strengthbar { width: 1px; background: #000; }
-->
</style>
<script type="text/javascript">
<!--
var minimum = 4;
var fair = 6;
var strength_label = Array( 'Too short', 'Weak', 'Fair', 'Medium', 'Strong', 'Very Strong' );
var strength_color = Array( 'FF0000', 'FF9900', 'FFCC33', '99CC99', '00CC33', '006600' );
var strength_width = Array( '10', '20', '30', '50', '75', '100' );
function updatestrength( pw ) {
if(!pw){ var pw = document.getElementById('password').value.toString(); }
if(!pw){ return false; }
var strength = 0;
if( pw.length >= minimum ) {
strength = 1;
if(pw.length >= fair){
strength++;
}
if(/\d+/g.test(pw)){
strength++;
}
if(/\W+/g.test(pw)){
strength++;
}
if(/[a-z]+/g.test(pw) && /[A-Z]+/g.test(pw)){
strength++;
}
}
document.getElementById('strength').innerHTML = strength_label[ strength ] + ' ' + strength;
document.getElementById('strengthbar').style.backgroundColor = strength_color[ strength ];
document.getElementById('strengthbar').style.width = strength_width[ strength ]+'%';
}
//-->
</script>
<input type="text" name="password" id="password" value="" onkeyup="updatestrength();" />
<div id="strengthmeter"><div><div id="strengthbar"></div></div><p id="strength"></p></div>
1. You're missing a "#" when setting the background color. Change this line to this:
document.getElementById('strengthbar').style.backgroundColor = '#'+strength_color[ strength ];
2. You're using a global pattern with test. In practice, it's unusual to use test() with global patterns. If you remove the 'g' from your patterns, I think it will work as expected.
Hope that helps.