Thursday, April 23, 2015

How to show password strength using JQuery

Hello friends, I want to discuss about JQuery code to show password strengths when a user types in a password into password field.

Password security is necessary to keep our accounts safe from hackers. Generally we use common passwords to remember them easily. However we should use secured passwords so that it couldn't be guessed by anyone. Recently I had a client who wants to show the password strength when a user types his password. So I tried the Jquery code which is explained in this tutorial to check the password strengths. This code will use JQuery regular expressions to check the strength of a password typed by the user.

I have also provided the CSS in this tutorial to add style to the message which shows the strengths of password entered.

Please check the below JQuery code:

$('#pwd').keyup(function(e) { var strongPass = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g"); var midPass = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g"); var morePass = new RegExp("(?=.{6,}).*", "g"); if (false == morePass.test($(this).val())) { $('#msg').html('Please enter more characters'); } else if (strongPass.test($(this).val())) { $('#msg').className = 'ok'; $('#msg').html('Great! your password is strong.'); } else if (midPass.test($(this).val())) { $('#msg').className = 'alert'; $('#msg').html('Better, your password strength is medium.'); } else { $('#msg').className = 'error'; $('#msg').html('Sorry, your password is too weak.'); } return true; });

Here I have included the CSS to  add styles to the div when the password strength status changes while typing in the password filed.

CSS:
.error{ background:#BE4C39; color:#fff; }.alert{ background:#fd7c2acolor:#fff; }.ok{background:#3cc16ecolor:#fff; }

Below is the HTML code for the input field and the div that holds the message which shows the password strength.


<input type="password" name="pwd" id="pwd" /><span id="msg"></span>

 I used pwd as name and id in the above input fields and the respective id has been used in the JQuery code and "msg" is the id used for the span which holds the message for the password strength.

I hope this code will help you in your projects. Please don't hesitate to ask your queries in the comment section below. Thank you. Happy coding :)

0 comments: