我有一个带有 bootstrap
的 form
,效果很好。并且 jQuery 验证工作正常。到ajax
提交代码的时候,就出问题了。即使未验证 form
也可以提交作品。
假设我将一个字段留空并按下提交,它会突出显示空字段上的错误,但 ajax 仍会提交 form
。
如何停止操作并请求验证?
这是 form
标记:
<form id="booking" method="post" class="form" action="" >
....some input fields here....
<button type="submit" id="submit" class="btn btn-large btn-block btn-primary">Book Now</button>
</form>
这是 jQuery 验证:
$('form').validate({
rules: {
firstname: {minlength: 2, maxlength: 40, required: true},
lastname: {minlength: 2, maxlength: 40, required: true},
email: {email: true, required: true},
country: {required: true},
mobile: {minlength: 2, maxlength: 40, required: true},
address: {minlength: 3, required: true}
},
});
这部分是ajax()
提交:
$('#booking').on('submit', function(e) {
e.preventDefault();
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
$('#loader', form).html('<img src="http://www.fethiye-tours.com/assets/images/lightbox/loading.gif" /> Please Wait...');
$.ajax({
type: 'POST',
url: 'http://www.fethiye-tours.com/book.php',
data: post_data,
success: function(msg) {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});
});
最佳答案
引用 OP:
"submit works even if the form is not validated"
那是因为您的自定义 .on('submit')
处理程序覆盖了 jQuery 验证插件的内置提交处理程序。
引用the documentation for the jQuery Validation plugin ,
submitHandler (default: native form submit)
Type: Function()
Callback for handling the actual submit when the form is valid. Gets theform
as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it is validated.
换句话说,任何 .ajax()
代码都在 submitHandler
回调函数中,该回调函数仅在表单有效时触发。所以摆脱你的整个 .on('submit')
处理函数并改为这样做......
(顺便说一句:正确缩进/格式化的代码更适合每个人阅读和解决问题)
$(document).ready(function() {
$('#booking').validate({ // <- attach '.validate()' to your form
// any rules, options, and callbacks,
rules: {
firstname: {
// minlength: 2,
// maxlength: 40,
rangelength: [2,40], // <- combines minlength and maxlength rules
required: true
},
// more rules,
},
submitHandler: function(form) { // <- only fires when form is valid
$('#loader', $(form)).html('<img src="http://www.fethiye-tours.com/assets/images/lightbox/loading.gif" /> Please Wait...');
$.ajax({
type: 'POST',
url: 'http://www.fethiye-tours.com/book.php',
data: $(form).serialize(),
success: function(msg) {
$(form).fadeOut(500, function(){
$(form).html(msg).fadeIn();
});
}
}); // <- end '.ajax()'
return false; // <- block default form action
} // <- end 'submitHandler' callback
}); // <- end '.validate()'
}); // <- end DOM ready handler
看起来您不需要 post_url
变量,因为您已经在 .ajax()
中声明了 url
。不妨保存一行并对 post_data
做同样的事情。
关于Ajax 提交表单,即使它没有通过 Bootstrap 验证进行验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20893573/