我有一个简单的表单,上面有10个左右的字段。其中两个字段是“名字”和“姓氏”。验证规则对他们来说非常简单,但实际上并没有起作用。
代码:
<script src="../../Scripts/jquery.validate.1.9.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.tinysort.min.js" type="text/javascript"></script>
<script src="../../Scripts/additional-methods.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
//Add Text Only
jQuery.validator.addMethod("TextOnly", function (value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
}, "Only Characters from A-Z.");
});
$("#form").validate({
ignore: ".ignore",
debug: false,
rules: {
"FirstName": {
required: true,
minlength: 2,
maxlength: 100,
TextOnly: "^[a-zA-Z0-9\(\)\ \-\.]+$"
},
"LastName": {
required: true,
minlength: 2,
maxlength: 100,
TextOnly: "^[a-zA-Z0-9\(\)\ \-\.]+$"
}
},
messages: {
"FirstName": {
required: "Please enter the First Name."
, minlength: "First Name must be at least 2 characters."
, maxlength: "First Name may be no more than 100 characters."
, TextOnly: "The First Name may contain only letters, numbers, spaces, dashes '-', periods '.', and parentheses '(' ')'."
},
"LastName": {
required: "Please enter the Last Name."
, minlength: "Last Name must be at least 2 characters."
, maxlength: "Last Name may be no more than 100 characters."
, TextOnly: "The Last Name may contain only letters, numbers, spaces, dashes '-', periods '.', and parentheses '(' ')'."
}}
////Commenting the following out places the errors under each field, instead of in a single area.
, errorLabelContainer: $("#form div.error")
});
TextOnly验证器适用于许多事情,但对我来说很奇怪的是它允许某些字符通过并且不会调出错误。例如,我可以在First / Last Name字段中键入“***”,并将其视为有效内容。
不应该“通过”的字符: ! #$%&amp; *'“,
因此,如果我输入“as $%&amp; *'”,“在字段中,它会通过验证,无论正在进行正则表达式验证。
答案 0 :(得分:1)
你有一个名为TextOnly
的方法,但函数本身与它无关......它只是一个正则表达式求值器。如果你要打电话给它TextOnly
,你也可以建立你的“纯文本”正则表达式。
否则,the additional-methods.js
file已经包含一条规则,用于评估传递给它的正则表达式pattern
...
$("#form").validate({
rules: {
FirstName: {
required: true,
minlength: 2,
maxlength: 100,
pattern: /^[a-zA-Z0-9\(\)\ \-\.]+$/
}
},
messages: {
FirstName: {
pattern: "Only Characters from A-Z."
}
}
});