jquery.validate.1.9.js - 验证忽略正则表达式中未列出的内容

jquery.validate.1.9.js - validation ignoring things not listed in regex

我有一个简单的表单,上面有 10 个左右的字段。其中两个字段是 "First Name" 和 "Last Name"。验证规则对他们来说非常简单,但并没有真正起作用。

代码:

<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 名称字段中键入“***”,它会将其接受为有效内容。

"pass" 不应出现的字符: ! # $ % & * ' " ,

因此,如果我在字段中键入 "as $%&*'"",无论是否进行了正则表达式验证,它都会通过验证。

您有一个名为 TextOnly 的方法,但函数本身与此无关...它只是一个正则表达式求值器。如果您打算将其命名为 TextOnly,您不妨将 "text-only" 正则表达式构建到其中。

否则,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."
        }
    }
});

演示:http://jsfiddle.net/htb48ebu/