I have a function which verifies the Password
field and suggests the user to enter a strong password. I also have a label named Password Strength
, referring to the strength of a password (very weak, weak, medium, etc).
Code:
<tr>
<%= label "Password",:mandatory=>true %>
<td>
<input id="user_password" type="password" size="30" name="user[password]" onkeyup="chkPasswordStrength(this.value,document.getElementById('strendth'),document.getElementById('error'))">
</td>
<td id="strendth" class="strength5"><b>Password Strength</td>
</tr>
<tr><td></td>
My JavaScript:
function chkPasswordStrength(txtpass,strenghtMsg,errorMsg)
{
var desc = new Array();
desc[0] = "Very Weak";
desc[1] = "Weak";
desc[2] = "Better";
desc[3] = "Medium";
desc[4] = "Strong";
desc[5] = "Strongest";
errorMsg.innerHTML = ''
var score = 0;
//if txtpass bigger than 6 give 1 point
if (txtpass.length > 6) score++;
//if txtpass has both lower and uppercase characters give 1 point
if ( ( txtpass.match(/[a-z]/) ) && ( txtpass.match(/[A-Z]/) ) ) score++;
//if txtpass has at least one number give 1 point
if (txtpass.match(/\d+/)) score++;
//if txtpass has at least one special caracther give 1 point
if ( txtpass.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/) ) score++;
//if txtpass bigger than 12 give another 1 point
if (txtpass.length > 12) score++;
strenghtMsg.innerHTML = desc[score];
strenghtMsg.className = "strength" + score;
if (txtpass.length < 6)
{
errorMsg.innerHTML = "Password Should be Minimum 6 Characters"
errorMsg.className = "errorclass"
}
}
And I have a CSS as well to change the style of the Password Strength
label according to user input.
My CSS:
<style type="text/css">
.strength0
{
width:200px;
background:#B20E37;
text-align: center;
font-weight: bold;
}
.strength1
{
width:200px;
background:#D32847;
text-align: center;
font-weight: bold;
}
.strength2
{
width:200px;
background:#ff5f5f;
text-align: center;
font-weight: bold;
}
.strength3
{
width:200px;
background:#83D680;
text-align: center;
font-weight: bold;
}
.strength4
{
background:#4dcd00;
width:200px;
text-align: center;
font-weight: bold;
}
.strength5
{
background:#399800;
width:200px;
text-align: center;
font-weight: bold;
}
.errorclass
{
font-weight:bold;
font-size: 10px;
color: #4F080B;
font-family: Arial,
}
</style>
I'm just wondering is there a better way to re-write this code.