【问题标题】:How do I check if a string contains at least one number, letter, and character that is neither a number or letter?如何检查字符串是否至少包含一个数字、字母和既不是数字也不是字母的字符?
【发布时间】:2017-04-14 09:34:10
【问题描述】:

语言是javascript。

会通过的字符串:

JavaScript1*

Pu54 325

()9c

不会通过的字符串:

654fff

%^(dFE

我尝试了以下方法:

var matches = password.match(/\d+/g);
if(matches != null)
 {
        //password contains a number
        //check to see if string contains a letter
        if(password.match(/[a-z]/i))
        {
            //string contains a letter and a number
        }
 }

【问题讨论】:

  • 是的。我尝试了很多东西。

标签: javascript regex string numbers letter


【解决方案1】:

您可以使用正则表达式:

我从这里拿的:Regex for Password

var checkPassword = function(password){
    return !!password.match(/^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%* #+=\(\)\^?&])[A-Za-z\d$@$!%* #+=\(\)\^?&]{3,}$/);
};

我使用这个正则表达式:

至少 3 个字符,至少 1 个字母、1 个数字和 1 个特殊字符:

"^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%* #=+\(\)\^?&])[A-Za-z\d$@$!%* #=+\(\)\^?&]{3,}$"

这个正则表达式将强制执行这些规则:

至少一个英文字母,(?=.*?[A-Za-z])

至少一位数字,(?=.*\d)

至少一个特殊字符,(?=.[$@$!% #+=()\^?&]) 如果你喜欢,可以添加更多...

最小长度为 3 个字符 (?=.[$@$!% #?&])[A-Za-z\d$@$!%* #+=()\ ^?&]{3,} 包含空格

如果你想添加更多的特殊字符,你可以像我添加'('一样将它添加到Regex中(你需要在两个地方添加它)。

对于那些问自己这两个感叹号是什么的人来说,答案是:What is the !! (not not) operator in JavaScript?

【讨论】:

  • 太完美了。谢谢!
  • @michael-drum 2 个感叹号是函数始终返回布尔值 - 看看这个stackoverflow.com/questions/784929/…
  • @michael-drum 那么您为什么不将此答案标记为“您的问题的答案”?
  • 到目前为止,我知道它不适用于空格或“+”。包含这些字符的字符串应返回 true;
  • @michael-drum 您应该将它们添加到特殊字符列表中 - 像这样 /^(?=.*[A-Za-z])(?=.*\d)(?= .*[$@$!%* #+=?&])[A-Za-z\d$@$!%* #+=?&]{3,}$/
猜你喜欢
  • 2017-03-13
  • 2016-07-20
  • 1970-01-01
  • 2012-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多