【问题标题】:Validation for passwords with special characters验证带有特殊字符的密码
【发布时间】:2020-10-05 13:57:39
【问题描述】:

我想为我的密码添加特殊字符验证。我的问题是当我使用 '%' 时它不起作用。如何正确添加特殊字符的验证?

$.validator.addMethod("pwcheck", function(value) {
  return /^[A-Za-z0-9\d=!\-@._*]*$/.test(value) // consists of only these
      && /[a-z]/.test(value) // has a lowercase letter
      && /[A-Z]/.test(value) // has a upper letter
      && /[!,%,&,@,#,$,^,*,?,_,~]/.test(value) // has a symbol
      && /\d/.test(value) // has a digit
});

【问题讨论】:

  • @Mandy8055 是的,谢谢
  • @Mandy8055 怎么样?有没有更好的办法?
  • @Mandy8055 是的,你明白了我的要求
  • 您需要删除[!,%,&,@,#,$,^,*,?,_,~] ([!%&@#$^*?_~]) 中的所有逗号。如果字符类要包含逗号,85个没有坏处,如果没有,文本中的逗号将满足该字符类的要求。

标签: javascript jquery regex validation


【解决方案1】:

您可以单独使用一个正则表达式来满足您的要求。你可以试试下面的正则表达式:

^(?=\D\d)(?=[^A-Z]*[A-Z])(?=[^a-z]*[a-z])(?=[^-!@._*#%]*[-!@._*#%])[-A-Za-z0-9=!@._*#%]*$

上述正则表达式的解释:

^, $ - 分别表示行的开始和结束。

(?=\D*\d) - 表示积极的环顾四周,至少断言一个数字。

(?=[^A-Z]*[A-Z]) - 表示肯定的环视,它至少断言一个大写字母。

(?=[^a-z]*[a-z]) - 表示肯定的环视,至少断言一个小写字母。

(?=[^-!@._*#%]*[-!@._*#%]) - 代表一个积极的环顾四周,它至少在列出的一个符号中断言。您可以根据需要添加更多符号。

[-A-Za-z0-9=!@._*#%]* - 匹配列出的字符中的零个或多个。您可以相应地添加更多符号。

你可以在here.找到上述正则表达式的demo

上述正则表达式在 javascript 中的示例实现:

const myRegexp = /^(?=[^\d\n]*\d)(?=[^A-Z\n]*[A-Z])(?=[^a-z\n]*[a-z])(?=[^-!@._*#%\n]*[-!@._*#%])[-A-Za-z0-9=!@._*#%]*$/gm; // Using \n for demo example. In real time no requirement of the same.
const myString = `thisisSOSmepassword#
T#!sIsS0om3%Password
thisisSOSmepassword12
thisissommepassword12#
THISISSOMEPASSWORD12#
thisisSOMEVALIDP@SSWord123
`;
// 1. doesn't contain a digit --> fail
// 3. doesn't contain a symbol --> fail
// 4. doesn't contain an Upper case letter --> fail
// 5. doesn't contain a lowercase letter --> fail
let match;
// Taken the below variable to store the result. You can use if-else clause if you just want to check validity i.e. valid or invalid.
let resultString = "";
match = myRegexp.exec(myString);
while (match != null) {
  resultString = resultString.concat(match[0] + "\n");
  match = myRegexp.exec(myString);
}
console.log(resultString);

参考资料:

  1. 推荐阅读:Principle of Contrast.

【讨论】:

  • 一个更好的主意是在这样的正则表达式中使用principle of contrast,使用/^(?=\D*\d)(?=[^A-Z]*[A-Z])(?=[^a-z]*[a-z])(?=[^-!@._*#%]*[-!@._*#%])[-A-Za-z0-9=!@._*#%]*$/
  • 你的演示错了,here is the right one。您不是在 regex101 针对单独的字符串进行测试,而是在针对单个多行字符串进行测试。这不是您在现实生活中所拥有的,因此您需要从否定字符类中排除换行符。您可以在 regex101 中诱骗人们相信奇怪的事情。谨慎使用它。
  • 我的意思是说你的“但它没有按应有的方式工作”是错误的:我的顶级评论正则表达式就像在具有现实生活中的字符串输入的真实代码中一样。
  • 我没有生气。请阅读我的Bonus: My regex works at regex101.com, but not in... anwer 中的line-breaks 段落。
  • 感谢@WiktorStribiżew 建议改进答案。
猜你喜欢
  • 2021-10-12
  • 1970-01-01
  • 2011-09-06
  • 2020-10-16
  • 1970-01-01
  • 1970-01-01
  • 2014-03-03
  • 2014-05-10
  • 1970-01-01
相关资源
最近更新 更多