正则表达式用于密码验证

时间:2010-03-03 09:29:14

标签: javascript regex

任何人都可以帮我创建密码验证的正则表达式。

条件是“密码必须包含8个字符,并且至少包含一个数字,一个字母和一个唯一字符,例如!#$%&? "

6 个答案:

答案 0 :(得分:55)

^.*(?=.{8,})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$%&? "]).*$

---

^.*              : Start
(?=.{8,})        : Length
(?=.*[a-zA-Z])   : Letters
(?=.*\d)         : Digits
(?=.*[!#$%&? "]) : Special characters
.*$              : End

答案 1 :(得分:7)

试试这个

((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W]).{6,20})

上述正则表达式的描述:

(           # Start of group
  (?=.*\d)      #   must contains one digit from 0-9
  (?=.*[a-z])       #   must contains one lowercase characters
  (?=.*[\W])        #   must contains at least one special character
              .     #     match anything with previous condition checking
                {8,20}  #        length at least 8 characters and maximum of 20 
)           # End of group

“/ W”会增加可用于密码和坑的字符范围,可以更安全。

答案 2 :(得分:6)

您可以轻松地完成每项要求(例如,最少8个字符:.{8,}将匹配8个或更多字符)。

要合并它们,您可以使用“正向前瞻”将多个子表达式应用于相同的内容。像(?=.*\d.*).{8,}这样的东西可以匹配一个(或多个)前瞻数字和8个或更多字符。

所以:

(?=.*\d.*)(?=.*[a-zA-Z].*)(?=.*[!#\$%&\?].*).{8,}

记住要逃避元字符。

答案 3 :(得分:5)

具有以下条件的密码:

  1. 至少1位数
  2. 至少2个特殊字符
  3. 至少1个字母字符
  4. 没有空格

    'use strict';
    (function() {
        var foo = '3g^g$';
    
        console.log(/^(?=.*\d)(?=(.*\W){2})(?=.*[a-zA-Z])(?!.*\s).{1,15}$/.test(foo));
    
        /**
         * (?=.*\d)         should contain at least 1 digit
         * (?=(.*\W){2})    should contain at least 2 special characters
         * (?=.*[a-zA-Z])   should contain at least 1 alphabetic character
         * (?!.*\s)         should not contain any blank space
         */
    })();
    

答案 4 :(得分:1)

您可以为javascript验证制作自己的正则表达式;

        (/^
        (?=.*\d)                //should contain at least one digit
        (?=.*[a-z])             //should contain at least one lower case
        (?=.*[A-Z])             //should contain at least one upper case
        [a-zA-Z0-9]{8,}         //should contain at least 8 from the mentioned characters

        $/)

示例: - /^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9]{7,}$/

答案 5 :(得分:0)

var regularExpression = new RegExp("^^(?=.*[A-Z]{"+minUpperCase+",})" +
    "(?=.*[a-z]{"+minLowerCase+",})(?=.*[0-9]{"+minNumerics+",})" +
    "(?=.*[!@#$\-_?.:{]{"+minSpecialChars+",})" +
    "[a-zA-Z0-9!@#$\-_?.:{]{"+minLength+","+maxLength+"}$");
if (pswd.match(regularExpression)) {
    //Success
}