Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

javascript - jQuery password strength checker

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);
        });
     });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...