我遇到过类似的问题。我通过在验证之前删除表单的操作和方法来解决它们,然后在验证后将它们添加回来。这是我写的验证器:
var Validator = function (formSelector) {
this.formSelector = formSelector;
// $(formSelector).submit(function() {return false;});
this.Action = $(formSelector).attr("action");
this.Method = $(formSelector).attr("method");
$(formSelector).attr("action",function(){return ""}).attr("method",function(){return ""});
var donotsubmit = false;
var notjustcheckbox = false;
var checknotchecked = false;
this.Required = new Array();
this.Email = new Array();
this.validate = function () {
this.form = $(this.formSelector);
var i = 0;
for (i in this.Required){
$(this.Required[i]).attr("value", function(index,attr){
// Check on checkboxes...
if (this.getAttribute("type") == "checkbox"){
if (this.checked == false){
checknotchecked = true;
donotsubmit = true;
} else {
}
} else {
if (attr == "" || attr == undefined){
this.style.border = "1px solid red";
notjustcheckbox = true;
donotsubmit = true;
} else {
this.style.border = "1px solid green";
}
}
});
}
i = 0;
for (i in this.Email){
$(this.Email[i]).attr("value", function(index,email){
var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i ;
if (filter.test(email) == true || filter.test(email) == "true") {
this.style.border = "1px solid green";
} else if (filter.test(email) == false) {
donotsubmit = true;
notjustcheckbox = true;
this.style.border = "1px solid red";
}
});
}
if (donotsubmit == true){
if (checknotchecked == true && notjustcheckbox == true){
alert("Please correct the fields in red and check the required checkboxes");
} else if (checknotchecked == true && notjustcheckbox == false){
alert("Please check the required checkboxes");
} else {
alert("Please correct the fields in red");
}
checknotchecked = false;
notjustcheckbox = false;
donotsubmit = false;
} else {
$(formSelector).attr({action : ''+this.Action+''});
$(formSelector).attr({method : ''+this.Method+''});
$(formSelector).submit();
}
return true;
};
};
你可以像这样实现它:
$(document).ready(function(){
var myForm = new Validator("#formId");
myForm.Required = new Array("input.lightborder");
myForm.Email = new Array("#email");
$("#form-submit-button-id").click(function(){
myForm.validate();
});
});
您可以为必填字段添加 CSS 选择器。电子邮件必须是唯一的。