To analyse the strength of a password we need to parse the contents of a textfield every time the contents change.

For the purposes of this tutorial we’ll use the following thresholds:

Too Short – less than 4 characters

Fair – less than 7 characters

Medium – 7 or more characters (characters only, no numbers)

Strong – 7 or more characters including at least 1 number

To start with let’s define some CSS styles:

Styles for the Tutorials

<style media=”all” type=”text/css”>

body {

background-color: #858585;

color: #EEEEEE;

font-family: Tahoma, sans-serif;

font-size: 11px;

}

input {

background-color: #EEEEEE;

border: 1px solid #333333;

color: #333333;

font-family: Tahoma, sans-serif;

font-size: 11px;

margin-bottom: 20px;

}

</style>

We have an image for each strength – you can use these or create your own:

The next thing to do is to load these four images into an array so they can be displayed as and when we need them – we simply create four Image objects and define the src attribute.

Preload Images into Array

var minpwlength = 4;

var fairpwlength = 7;

var STRENGTH_SHORT = 0; // less than minpwlength

var STRENGTH_WEAK = 1; // less than fairpwlength

var STRENGTH_FAIR = 2; // fairpwlength or over, no numbers

var STRENGTH_STRONG = 3; // fairpwlength or over with at least one number

img0 = new Image();

img1 = new Image();

img2 = new Image();

img3 = new Image();

img0.src = ‘images/tooshort.jpg’;

img1.src = ‘images/fair.jpg’;

img2.src = ‘images/medium.jpg’;

img3.src = ‘images/strong.jpg’;

var strengthlevel = 0;

var strengthimages = Array( img0.src,

img1.src,

img2.src,

img3.src );

The first function we’ll need to write is one that checks if the password is too small – it’s simple – it just checks the length of the string:

Is Too Small

function istoosmall( pw ) {

if( pw.length < minpwlength ) {

return true;

}

else {

return false;

}

}

If it’s not too small we need to check if it constitutes fair, i.e. 4 – 6 characters (it works in the same way as the previous function).

Is Fair

function isfair( pw ) {

if( pw.length < fairpwlength ) {

return false;

}

else {

return true;

}

}

Then we need to check for at least one number – if it has a number it’s strong, if it hasn’t it’s fair. We use the charAt() function to loop through each of the characters and then use isNaN to find out if the current character is an integer.

hasnum Function

function hasnum( pw ) {

var hasnum = false;

for( var counter = 0; counter < pw.length; counter ++ ) {

if( !isNaN( pw.charAt( counter ) ) ) {

hasnum = true;

}

}

return hasnum;

}

Now we need a function to manage the previous three – this next function is called every time they key is pressed: