admin管理员组文章数量:1321053
I have the following block of code:
$(document).ready(function(){
$("#form").submit(function(ev) {
ev.preventDefault();
$.ajax({
type: "POST",
url: "proxy.php",
data: postData,
success: function(data) {
window.location = "thankyou.php";
},
error:function(xhr, ajaxOptions, thrownError){
console.log(xhr.responseText);
}
});
});
$("#form").validate({
//a bunch of validation here
});
});
The issue is that this will continue to post using ajax even though some validation fails.. why is this? Am I using ev.preventDefault() the wrong way? What I want is that for the form to be validated before I send a POST if some validation fails then just cancel, I believe that is through ev.preventDefault()?
I have the following block of code:
$(document).ready(function(){
$("#form").submit(function(ev) {
ev.preventDefault();
$.ajax({
type: "POST",
url: "proxy.php",
data: postData,
success: function(data) {
window.location = "thankyou.php";
},
error:function(xhr, ajaxOptions, thrownError){
console.log(xhr.responseText);
}
});
});
$("#form").validate({
//a bunch of validation here
});
});
The issue is that this will continue to post using ajax even though some validation fails.. why is this? Am I using ev.preventDefault() the wrong way? What I want is that for the form to be validated before I send a POST if some validation fails then just cancel, I believe that is through ev.preventDefault()?
Share Improve this question asked Sep 11, 2011 at 15:57 aherlambangaherlambang 14.4k54 gold badges153 silver badges255 bronze badges2 Answers
Reset to default 6Before doing your ajax request, test if the form is valid:
if (!$(this).valid()) return;
You may want to try the submitHandler option too: http://docs.jquery./Plugins/Validation/validate#options
In the validate
settings you can specify the submitHandler
which takes a function. You can have all the validation login inside submitHandler and return true/false conditionally. Returning false
in submitHandler will not submit the form. Try this
$("form").validate({
submitHandler: function(form) {
// if validation is successfull return true else false.
}
});
本文标签: javascriptjQuery preventDefault to do validation before POSTStack Overflow
版权声明:本文标题:javascript - jQuery preventDefault to do validation before POST - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742093076a2420383.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论