[英]regex not validating
I have the following regex for password validation in javascript: 我在javascript中有以下用于密码验证的正则表达式:
^[!#\$%\(\)\*,\-\./:;=\?@\[\\\]\^_`\{\|\}~a-zA-Z0-9]*$
<script type="text/javascript">
var regex = "^[!#\$%\(\)\*,\-\./:;=\?@\[\\\]\^_`\{\|\}~a-zA-Z0-9]*$";
var value = 'test';
if (value.match(regex) == false) {
alert('password invalid');
}
</script>
The regex rules are: 正则表达式规则是:
However, the regex doesn't seem to work. 但是,正则表达式似乎不起作用。 It matches any characters.
它匹配任何字符。 How do I fix this?
我该如何解决?
Using positive lookahead your regex can be validated in one single match call. 使用正向预测可以在一次匹配调用中验证正则表达式。 Use this regex:
使用这个正则表达式:
var regex =
/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!#$%()\*,/:;=?@\[\\\]\^_`{}|.-])^.{12,25}$/;
var value = 'aaaAaaaaa?test2';
if (!value.match(regex))
document.writeln('invalid');
else
document.writeln('valid');
尝试:
/^(?=(?:.*[a-z]){1})(?=(?:.*[A-Z]){1})(?=(?:.*\d){1})(?=(?:.*[!#$%()*,-./:;=?@[]^_`{|}~ ]){1,}).{12,25}$/
This regex works: 这个正则表达式有效:
^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[-|^!#$%()*,./:;=?@_`{}~[\]]).{12,25}$
It uses the technique of lookahead to make sure there is at least 1 digit, lowercase char, ... 它使用先行技术来确保至少有1位数字,小写字母,...
Also, look at Regex expression for password rules for a similar challenge 另外,查看类似挑战的密码规则的Regex表达式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.