javascript 密码强度验证的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15678619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:40:08  来源:igfitidea点击:

Regular Expression for Password Strength Validation

javascriptregexvalidationpasswords

提问by Matthew Layton

I have written a regular expression which could potentially be used for password strength validation:

我写了一个正则表达式,它可能用于密码强度验证:

^(?:([A-Z])*([a-z])*(\d)*(\W)*){8,12}$

The expression consists of four groups:

该表达式由四组组成:

  1. Zero or more uppercase characters
  2. Zero or more lowercase characters
  3. Zero or more decimal digits
  4. Zero or more non-word characters (!, £, $, %, etc.)
  1. 零个或多个大写字符
  2. 零个或多个小写字符
  3. 零个或多个十进制数字
  4. 零个或多个非单词字符(!、£、$、% 等)

The way I want it to work is to determine how many of the groups have been matched in order to determine the strength of the password. so for example, if only 1 group is matched, it would be weak. If all four groups were matched, it would be strong.

我希望它工作的方式是确定匹配了多少组以确定密码的强度。因此,例如,如果仅匹配 1 个组,则它会很弱。如果所有四组都匹配,那将是强大的。

I have tested the expression using Rubular (a Ruby regular expression editor).

我已经使用Rubular(一个 Ruby 正则表达式编辑器)测试了表达式

Here I can see visually, how many groups are matched, but I want to do this in JavaScript. I wrote a script that returns the number of matched groups, but the results were not the same as I can see in Rubular.

在这里,我可以直观地看到匹配了多少组,但我想在 JavaScript 中执行此操作。我写了一个脚本来返回匹配组的数量,但结果与我在 Rubular 中看到的不一样。

How can I achieve this in JavaScript? and is my regular expression up to the task?

我如何在 JavaScript 中实现这一点?我的正则表达式能胜任这项任务吗?

回答by sp00m

I think you'll have to check each group independently. Pseudo-code:

我认为您必须独立检查每个组。伪代码:

bool[] array = {};
array[0] = pwd.match(/[A-Z]/);
array[1] = pwd.match(/[a-z]/);
array[2] = pwd.match(/\d/);
array[3] = pwd.match(/[!_.-]/);

int sum = 0;
for (int i=0; i<array.length; i++) {
    sum += array[i] ? 1 : 0;
}

switch (sum) {
    case 0: print("weird..."); break;
    case 1: print("weak"); break;
    case 2: print("ok"); break;
    case 3: print("strong"); break;
    case 4: print("awesome"); break;
    default: print("weird..."); break;
}

回答by Matthew Layton

Here was my final solution based on sp00m's answer:

这是我基于 sp00m 回答的最终解决方案:

function testPassword(pwString) {
    var strength = 0;

    strength += /[A-Z]+/.test(pwString) ? 1 : 0;
    strength += /[a-z]+/.test(pwString) ? 1 : 0;
    strength += /[0-9]+/.test(pwString) ? 1 : 0;
    strength += /[\W]+/.test(pwString) ? 1 : 0;

    switch(strength) {
        case 3:
            // its's medium!
            break;
        case 4:
            // it's strong!
            break;
        default:
            // it's weak!
            break;
    }
}

I've added this purely for reference, however have accepted sp00m's answer since it was their answer that let me to this solution.

我添加这个纯粹是为了参考,但是已经接受了 sp00m 的回答,因为正是他们的回答让我有了这个解决方案。

回答by Licson

You can do it by separating each group out and match them one by one, like this:

您可以通过将每个组分开并一一匹配来实现,如下所示:

var level = 0;
var input = '';//user input goes here
switch(true){
    case /^(?:([A-Z])*){8,12}$/.test(input):
    level = 1;
    break;

    case /^(?:([A-Z])*([a-z])*){8,12}$/.test(input):
    level = 2;
    break;

    case /^(?:([A-Z])*([a-z])*(\d)*){8,12}$/.test(input):
    level = 3;
    break;

    case /^(?:([A-Z])*([a-z])*(\d)*(\W)*){8,12}$/.test(input):
    level = 4;
    break;
}

The levelvariable goes from 1 (the weakest) to 4 (the strongest).

level变量超出从1(最弱)至4(最强)。

回答by user1710825

Check out this: http://jsfiddle.net/43tu58jf/

看看这个:http: //jsfiddle.net/43tu58jf/

function isSimpleStrongLevel(password){
    var stringsOptions = ['123456', '123abc', 'abc123', '654321', '012345', 'password', '123pass', 'pass123', '123456abc'];
    return stringsOptions.indexOf(password) != -1;
}
function getStrongLevel(password) {
    var level = 0;
    level += password.length > 6 ? 1 : 0;
    level += /[!@#$%^&*?_~]{2,}/.test(password) ? 1 : 0;
    level += /[a-z]{2,}/.test(password) ? 1 : 0;
    level += /[A-Z]{2,}/.test(password) ? 1 : 0;
    level += /[0-9]{2,}/.test(password) ? 1 : 0;
    return level;
}

var password = '123456';
var isSimple = isSimpleStrongLevel(password);
var level = getStrongLevel(password);
console.log(isSimple, level);

回答by rktuxyn

Try it ==>

试试吧==>

var PasswordStrength = function () {
    var p_worker = {
        checkMark: function ( msg, mark ) {
            let strength = "Required!!!", status = true;
            switch ( mark ) {
                case 1: strength = '<b style="color:rgb(200, 200, 200)"> Password strength: Weak...</b>'; break;
                case 2: strength = '<b style="color:rgb(200, 200, 200)"> Password strength: Semi-weak...</b>'; break;
                case 3: strength = '<b style="color:green"> Password strength: Medium...</b>'; break;
                case 4: strength = '<b style="color:green"> Password strength: Strong...</b>'; break;
                default: status = false; break;
            }
            return { status: status/*[is valid or not]*/, cur_strength: strength/**[strength msg]*/, req_msg: msg/**[required msg]*/, mark: mark/**[strength mark]*/ };
        },
        setting: {
            n: { rgx: /[0-9]/, msg: '1 Numeric character' },
            c: { rgx: /[A-Z]/, msg: '1 Alphabet character' },
            s: { rgx: /[a-z]/, msg: '1 Small character' },
            sp: { rgx: /[@#$\.%^&+=]/, msg: '1 Special character' },
        }
    };
    return {
        check: function ( value ) {
            let msg = "", mark = 0, c = 0;
            for ( let i in p_worker.setting ) {
                if ( !p_worker.setting[i]['rgx'].test( value ) ) {
                    if ( c === 3 ) {
                        msg += '<d style="color:rgba(219, 177, 177, 0.96)">[*] ' + p_worker.setting[i]['msg'] + '</d>';
                        c++; continue;
                    }
                    msg += '<d style="color:rgba(219, 177, 177, 0.96)">[*] ' + p_worker.setting[i]['msg'] + ',</d></br>';
                    c++; continue;
                }
                if ( c === 3 ) {
                    msg += '<img src="/image/accept.png" /> <d style="color:green">' + p_worker.setting[i]['msg'] + '</d>';
                    mark++; c++; continue;
                }
                msg += '<img src="/image/accept.png" /> <d style="color:green">' + p_worker.setting[i]['msg'] + ',</d></br>';
                mark++; c++;
            }
            return p_worker.checkMark( msg, mark );
        }
    }
}();

Use ==>

使用 ==>

PasswordStrength.check( "1234$#" );

回答by websky

my example

我的例子

JS/jQuery

JS/jQuery

$( "#password" ).change(function ()
{
    strongPassword();
});

/**
 * @author websky
 */
function strongPassword() {
    var p = document.getElementById('password').value;
    var label1 = 0; 
    var label2 = 0; 
    var label3 = 0; 
    var label4 = 0; 
    var label5 = 0;
    if (p.length > 6) {//min length
        label1 = 1;
    }
    if (/[!@#$%^&*?_~]{2,}/.test(p)) {//min 2 special characters
        label2 = 1;
    }
    if (/[a-z]{2,}/.test(p)) {//min 2 a-z
        label3 = 1;
    }
    if (/[A-Z]{2,}/.test(p)) {//min 2 A-Z
        label4 = 1;
    }
    if (/[0-9]{2,}/.test(p)) {//min 2 0-9
        label5 = 1; 
    }

    var strong_password = label1 + label2 + label3 + label4 + label5;

    if(strong_password > 0){
        //Here your action
        //
        //var progressbar = strong_password * 20; 
        //$( "#progressbar" ).progressbar({value: progressbar}); <== I use jQuery progessbar
    } 
}