Javascript 密码正则表达式:“至少 1 个字母、1 个数字、1 个特殊字符,并且不应以特殊字符开头”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27938415/
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-08-23 00:58:12  来源:igfitidea点击:

Regex for Password: "Atleast 1 letter, 1 number, 1 special character and SHOULD NOT start with a special character"

javascriptregexasp.net-mvc

提问by adiga

I need a regular expression for a password field.

我需要一个密码字段的正则表达式。

The requirement is:

要求是:

  1. The password Must be 8 to 20 characters in length

  2. Must contain at least one letterand one numberand a special character from !@#$%^&*()_+.

  3. Should not start with a special character

  1. 密码长度必须为 8 到 20 个字符

  2. 必须至少包含一个字母一个数字以及一个来自!@#$%^&*()_+.

  3. 不应以特殊字符开头

I have tried

我试过了

^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*()_+])[A-Za-z\d!@#$%^&*()_+]{8,20}

It works but how do you restrict special characters from beginning the password? Also if you have a more efficient regex than the one mentioned above please suggest.

它有效,但是如何限制特殊字符从密码开始?此外,如果您有比上述更有效的正则表达式,请提出建议。

Thank you

谢谢

回答by nu11p01n73R

Its simple, just add one more character class at the begining

很简单,在开头多加一个字符类

^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*()_+])[A-Za-z\d][A-Za-z\d!@#$%^&*()_+]{7,19}$
  • [A-Za-z\d]Ensures that the first character is an alphabet or digit.

  • [A-Za-z\d!@#$%^&*()_+]{7,19}will match minimum 7 maximum 19 character. This is required as he presceding character class would consume a single character making the total number of characters in the string as minimum 8 and maximum 20.

  • $Anchors the regex at the end of the string. Ensures that there is nothing following our valid password

  • [A-Za-z\d]确保第一个字符是字母或数字。

  • [A-Za-z\d!@#$%^&*()_+]{7,19}将匹配最少 7 个最多 19 个字符。这是必需的,因为他前面的字符类将消耗单个字符,使字符串中的字符总数最少为 8,最多为 20。

  • $将正则表达式锚定在字符串的末尾。确保我们的有效密码后面没有任何内容

Regex Demo

正则表达式演示

var pattern = new RegExp(/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*()_+])[A-Za-z\d][A-Za-z\d!@#$%^&*()_+]{7,19}$/);

console.log(pattern.test("!@#123asdf!@#"));

console.log(pattern.test("123asdf!@#"));

console.log(pattern.test("12as#"));