I'm quite new to jQuery, and I've written a simple function to check the strength of a password for each keypress.
The idea is that every time a user enters a character, the contents is evaluated to test the strengh of the password they have entered... I'm sure everyone has seen these before.
Anyhow, the logic I have used is that no password begins with a value of 1. When a lower-case character is used, the score increments to 2. When a digit is used the score increments by 1 again, same for when an uppercase character is used and when the password becomes 5 or more characters long.
What is returned is the strength of the password so far as a value from 1 to 5 every time a key is pressed.
So, about my question. The way that I've done it doesn't seem very jQuery like... almost like I may as well have just done straight javascript. Also I was wondering about my logic. Have I done anything done or overlooked something? Any suggestions from smarter people than myself?
Any suggestions or advice would be appreciated.
$(document).ready(function(){ $("#pass_strength").keyup(function() { var strength = 1; /*length 5 characters or more*/ if(this.value.length >= 5) { strength++; } /*contains lowercase characters*/ if(this.value.match(/[a-z]+/)) { strength++; } /*contains digits*/ if(this.value.match(/[0-9]+/)) { strength++; } /*contains uppercase characters*/ if(this.value.match(/[A-Z]+/)) { strength++; } alert(strength); }); });
jQuery('. validatedForm'). validate({ rules: { password: { required: true, minlength: 5 }, password_confirm: { required: true, minlength: 5, equalTo: "#password" } } });
This can be done by document. getElementById() function, which selects an element by its id. var text1 = document. getElementById("username");
The best way is to take an existing plugin as TJB suggested.
As to your question about the code itself, a nicer way is to write it like that:
var pass = "f00Bar!"; var strength = 1; var arr = [/.{5,}/, /[a-z]+/, /[0-9]+/, /[A-Z]+/]; jQuery.map(arr, function(regexp) { if(pass.match(regexp)) strength++; });
(Modified to correct syntax errors.)
I would suggest evaluating an existing jQuery password strength plugin. (unless your just doing it as an exercise)
Here are a few links I found:
http://www.visual-blast.com/javascript/password-strength-checker/
http://phiras.wordpress.com/2007/04/08/password-strength-meter-a-jquery-plugin/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With