我有一个表单要求字段没有任何特殊字符或数字。目前它适用于:
abc
:没有错误。123
:错误。!@#$
:错误。问题是当我添加#$%abc
或abc123
之类的内容时,它不会产生我期望的错误。
我正在使用的功能如下:
$.validator.addMethod("checkallowedchars", function (value) {
var pattern = new RegExp('[A-Za-z]+', 'g');
return pattern.test(value)
}, "The field contains non-admitted characters");
JSFiddle显示我正在使用的函数/正则表达式:http://jsfiddle.net/nmL8maa5/
答案 0 :(得分:1)
正确的答案之一是:
return /^[A-Z]+$/i.test(value);
并添加
checkallowedchars: true,
遵守规则。
请参阅updated demo fiddle(以下内容对我不起作用,不知道为什么)。
$(document).ready(function () {
$.validator.addMethod("pwcheckallowedchars", function (value) {
return /^[a-zA-Z0-9!@#$%^&*()_=\[\]{};':"\\|,.<>\/?+-]+$/.test(value) // has only allowed chars letter
}, "The password contains non-admitted characters");
$.validator.addMethod("checkallowedchars", function (value) {
return /^[A-Z]+$/i.test(value);
}, "The field contains non-admitted characters");
$.validator.addMethod("pwcheckspechars", function (value) {
return /[!@#$%^&*()_=\[\]{};':"\\|,.<>\/?+-]/.test(value)
}, "The password must contain at least one special character");
$.validator.addMethod("pwcheckconsecchars", function (value) {
return ! (/(.)\1\1/.test(value)) // does not contain 3 consecutive identical chars
}, "The password must not contain 3 consecutive identical characters");
$.validator.addMethod("pwchecklowercase", function (value) {
return /[a-z]/.test(value) // has a lowercase letter
}, "The password must contain at least one lowercase letter");
$.validator.addMethod("pwcheckrepeatnum", function (value) {
return /\d{2}/.test(value) // has a lowercase letter
}, "The password must contain at least one lowercase letter");
$.validator.addMethod("pwcheckuppercase", function (value) {
return /[A-Z]/.test(value) // has an uppercase letter
}, "The password must contain at least one uppercase letter");
$.validator.addMethod("pwchecknumber", function (value) {
return /\d/.test(value) // has a digit
}, "The password must contain at least one number");
$('#myform').validate({
// other options,
rules: {
"firstname.fieldOne": {
required: true,
checkallowedchars: true,
pwchecklowercase: true,
pwcheckuppercase: true,
pwchecknumber: true,
pwcheckconsecchars: true,
pwcheckspechars: true,
pwcheckallowedchars: true,
minlength: 8,
maxlength: 20
}
}
});
});
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/additional-methods.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
<input type="text" name="firstname.fieldOne" /><br/>
<br/>
<input type="submit" />
</form>
您的代码中存在两个问题:
#$%abc
包含3个字母,因此符合条件。/g
修饰符RegExp.text()
。 This leads to unexpected behavior. 答案 1 :(得分:0)
使用此:
^[A-Za-z]+$
^
是字符串开始锚。$
是字符串结束锚。你应该使用它来让正则表达式从头到尾处理字符串,不包括中间字符串。