jQuery验证问题

时间:2011-03-27 21:55:13

标签: jquery validation

我正在尝试验证4个字段。最后两个验证行为正确,但前两个不起作用。如果我什么也没输入 - 表格仍然会有效。

这是该方法的jQuery:

jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
            phone_number = phone_number.replace(/\s+/g, ""); 
            return this.optional(element) || phone_number.length > 9 &&
            phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
        }, "Not a valid phone number");
        $("#advertisePost").validate({
            rules: {
                advRetailerName: {
                    required: true
                },
                advName: {
                    required: true
                },
                advPhone: {
                    required: true,
                    phoneUS: true
                },
                advEmail: {
                    required: true,
                    email: true
                }           
            },
            messages:{
                advRetailerName: {
                    required: "This is required."
                },
                advName: {
                    required: "This is required."
                },
                advPhone: {
                    required: "This is required.",
                    phoneUS: "This is an invalid phone number."
                },
                advEmail: {
                    required: "This is required",
                    email: "This is an invalid email"
                }
            }
        });

这是实际的表格本身:

 <form action="php/advertisePost.php" method="POST" id="advertisePost">
<table>
<tr>
    <td>Retailer Name</td><td><input type="text" id="advRetailerName" name="advRetailerName"/><br/><label for="advRetailerName" class="error" generated="true"></label></td>
</tr>
<tr>
    <td>Your Name</td><td><input type="text" id="advName" name="advName"/><br/><label for="advName" class="error" generated="true"></label></td>
</tr>
<tr>
    <td>Phone Number</td><td><input type="text" id="advPhone" name="advPhone"/><br/><label for="advPhone" class="error" generated="true"></label></td>
</tr>
<tr>
    <td>Email Address</td><td><input type="text" id="advEmail" name="advEmail"/><br/><label for="advEmail" class="error" generated="true"></label></td>
</tr>
</table>
    <input type="button" value="Submit" id="advSubmit"/>
</form>

我已经完美地制作了半打表格,但是我不明白为什么前两个字段没有遵循验证规则存在问题。有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

我只是简单地使用了这个插件。根据我的记忆,您所要做的就是在输入元素中添加一个“必需”类,以便验证器检查空字段。