使用JQuery验证表单时出现问题

时间:2013-09-13 00:33:58

标签: validation jquery jquery-validate

脚本

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js" type="text/javascript"></script>
<script src="jquery.validate.js" type="text/javascript"></script>
<script src="jquery.validate.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
    $(document).ready(function () {
        $("#Field2").rules("add", { regex: "^[a-zA-Z0-9]{0,3}$" });
        $.validator.addMethod(
                'regex',
                function (value, element, regexp) {
                    var re = new RegExp(regexp);
                    return this.optional(element) || re.test(value);
                }, "My Error Message");

        $('#MyForm').validate(
            {
                rules: {
                    Field1: {
                        required: false,
                        range: [1, 9999999999]
                    }
                },
                messages: {
                    Field1: {
                        range: jQuery.validator.format("Please enter a value between {0} and {1}.")
                    }
                }
                ,
                highlight: function (element) {
                    $(element).closest('.MyForm').removeClass('success').addClass('error');
                },
                success: function (element) {
                }
            });
    });                   

</script>

表格

<form action="#" id="MyForm" name="MyForm">
<table id="tblData">
    <tr>
        <td>
            <label>
                Field1</label>
            <input id="Field1" name="Field1" type="text" value="" />
        </td>
    </tr>
    <tr>
        <td>
            <label>
                Field2</label>
            <input id="Field2" name="Field2" />
        </td>
    </tr>
    <tr>
        <td>
            <span id="submitButton" class="k-button">Next</span>
            <input type="submit" class="button" name="submitButtonTest" id="submitButtonTest"
                value="Validation Test">
        </td>
    </tr>
</table>
</form>

问题

  1. $。data(...)未定义
  2. 未验证Field1。
  3. 未显示错误消息
  4. 的jsfiddle

    Demo is here

1 个答案:

答案 0 :(得分:2)

在为包含该表单的表单启用验证之前,无法为字段定义规则。所以你需要把

$("#Field2").rules("add", { regex: "^[a-zA-Z0-9]{0,3}$" });

$("#myForm").validate(...);

FIDDLE

如果要在添加规则时指定消息,可以执行以下操作:

$("#Field2").rules("add", {
    regex: "^[a-zA-Z0-9]{0,3}$",
    messages: {
        regex: "Must be 0 to 3 alphanumeric characters"
    }
});

请参阅.rules()

的文档