jQuery 密码强度检查器

2022-01-22 00:00:00 logic passwords jquery javascript

我是 jQuery 的新手,我编写了一个简单的函数来检查每次按键的密码强度.

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.

无论如何,我使用的逻辑是没有密码以值 1 开头.当使用小写字符时,分数增加到 2.当使用数字时,分数再次增加 1,同样当使用大写字符并且密码长度为 5 个或更多字符时.

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.

每次按下一个键时,返回的都是密码强度,从 1 到 5 的值.

What is returned is the strength of the password so far as a value from 1 to 5 every time a key is pressed.

那么,关于我的问题.我完成它的方式似乎不像 jQuery 那样......几乎就像我可能刚刚完成了直接的 javascript.我也想知道我的逻辑.我做了什么或忽略了什么?比我更聪明的人有什么建议吗?

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);
        });
     });

推荐答案

最好的方法是按照 TJB 的建议使用现有的插件.

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

相关文章