我正在使用以下代码验证我的表单。验证很顺利但提交表单时遇到问题。问题是:每次单击“发送表单”按钮时,表单都会提交到php文件,无论表单是否未经过验证。
我该如何解决?
我一直在研究submitHandler,但我不知道如何将它与ajax和序列化一起使用..
非常感谢!
<script>
$(document).ready(function(){
$("#form").validate({
rules: {
name: {
required: true
},
lname: {
required: true
}
},
messages: {
name: {
required: "* required"
},
lname: {
required: "* required"
}
}
}); //end validate
$('#form').submit(function() {
theUrl = 'form.php';
var params = $(this).serialize();
$.ajax ({
type: "POST",
url: theUrl,
data: params,
processData:false,
async:false,
success: function(result) {
//if (data != "") alert (data);
}
});
//return false;
}); //end submit
}); //end document ready
</script>
答案 0 :(得分:1)
您需要将AJAX请求代码放在validate插件的submitHandler
参数中。目前,AJAX请求正在submit()
事件上运行,与任何验证结果并行。试试这个:
$(document).ready(function(){
$("#form").validate({
rules: {
name: { required: true },
lname: { required: true }
},
messages: {
name: { required: "* required" },
lname: { required: "* required" }
},
submitHandler: function(form) {
theUrl = 'form.php';
var params = $(form).serialize();
$.ajax ({
type: "POST",
url: theUrl,
data: params,
processData: false,
async: false,
success: function(result) {
//if (data != "") alert (data);
}
});
}
}); //end validate
});