我需要验证 HTML 表单中的姓名、房间号和电话号码字段。我为每个规则编写了自定义规则并在脚本中调用它们。但是当输入无效时,这些和默认的 jQuery 规则不会引发错误。这是我的代码。
<script>
$(document).ready(function() {
jQuery.validator.addMethod("firstlastname", function(value, element){
return this.optional(element) || (/^[a-z]([-']?[a-z]+)*( [a-z]([-']?[a-z]+)*)+$/.test(value));
}, "Please Enter Your First and Last Name");
jQuery.validator.addMethod("roomnumber", function(value, element){
return this.optional(element) || (/^\d{3}\S{0,1}/.test(value));
}, "Invalid Room Number");
jQuery.validator.addMethod("phonenumber", function(value, element){
return this.optional(element) || (/^\d{3}\-\d{3}\-\d{4}$ | ^\d{10} | ^\(\d{3}\)\d{3}\-\d{4}$/.test(value));
}, "Invalid Phone Number Format");
$("#my_form").validate({
rules: {
name: {
required: true,
firstlastname: true
},
room_number: {
roomnumber: true
},
cell_phone: {
required: true,
phonenumber: true
}
},
messages: {
name: {
required: "First and Last Name is Required",
firstlastname: "Please Enter Your First and Last Name"
},
room_number: {
roomnumber: "Invalid Room Number"
},
cell_phone: {
required: "Phone Number is Required",
phonenumber: "Please Enter a Valid Phone Number"
}
},
errorPlacement: function(error, element) {
if (element.attr("name") == "Name") {
error.appendTo($("#nameValid"));
} else if (element.attr("name") == "Room_Number") {
error.appendTo($("#roomNumberValid"));
} else if (element.attr("name") == "Cell_Phone") {
error.appendTo($("#cellPhoneValid"));
}
}
});
});
</script>
这是HTML
<form id="my_form" method="post" >
<p>Name: </p>
<p>
<input name="name" style="width: 275px" type="text"/>
<span id="nameValid"></span>
</p>
<p>Room Number:</p>
<p>
<input name="room_number" type="text" maxlength="5"/>
<span id="roomNumberValid"></span>
</p>
<p>Cell Phone:</p>
<p> <input name="cell_phone" style="width: 192px" type="text" maxlength="13"/> <br/>
<span id="cellPhoneValid"></span>
</p>
我已经尝试过不同的 jquery 文件和 jquery validate 插件版本,它们都允许我提交无效输入。我在这里先向您的帮助表示感谢!