【发布时间】:2014-11-25 22:56:04
【问题描述】:
我目前创建了一个 AJAX 联系表单,我在我的网站上使用它并使用 BootstrapValidator 来验证字段。我在代码中有 e.PreventDefault() 行;但是,当我按下提交时,即使验证失败,表单也会提交(尽管错误消息会出现在表单上)。尽管遵循http://bootstrapvalidator.com/examples/ajax-submit/ 的示例,但我无法弄清楚如何阻止提交进行验证。有人有什么想法吗?
JSFiddle:http://jsfiddle.net/5dpm655v/1/
HTML
<form accept-charset="UTF-8" action="/echo/json/" data-remote="true" id="contact_form" method="post">
<label for="name">Name</label>
<div class="row margin-bottom-20">
<div class="col-md-7 col-md-offset-0">
<input class="form-control" id="name" name="name" type="text" />
</div>
</div>
<label for="email">Email</label>
<div class="row margin-bottom-20">
<div class="col-md-7 col-md-offset-0">
<input class="form-control" id="email" name="email" type="text" />
</div>
</div>
<label for="message">Message</label>
<div class="row margin-bottom-20">
<div class="col-md-11 col-md-offset-0">
<textarea class="form-control" id="message" name="message" rows="8"></textarea>
</div>
</div>
<p>
<button type="submit" class="btn-u">Send Message</button>
<span id="contact-form-success" style="display:none;">Message successfully sent. We'll be in touch shortly!</span>
<span id="contact-form-error" style="display:none;">Error: I'm sorry, we weren't able to successfully send your message. Please try again.</span>
</p>
</form>
jQuery
jQuery(document).ready(function() {
$('form#contact_form')
.bootstrapValidator({
fields: {
name: {
validators: {
notEmpty: {
message: 'Name is required and cannot be empty'
}
}
},
email: {
validators: {
notEmpty: {
message: 'Email is required and cannot be empty'
},
emailAddress: {
message: 'This is not a valid email address'
}
}
},
message: {
validators: {
notEmpty: {
message: 'Message is required and cannot be empty'
}
}
}
}
})
.on('success.form.bv', function(e) {
e.preventDefault();
var valuesToSubmit = $(this).serialize();
$.ajax({
url: $(this).attr('action'),
data: valuesToSubmit,
dataType: 'json',
type: 'POST',
success: function(data) {
$('input#name').val('');
$('input#email').val('');
$('textarea#message').val('');
$('#contact-form-success').show().fadeOut(10000);
},
error: function(data) {
$('#contact-form-error').show().fadeOut(10000);
}
});
});
});
【问题讨论】:
-
你的成功调用在
document.ready之外。 -
@anpsmn - 很好的解决了这个问题;但是,问题仍然存在。
标签: jquery ajax twitter-bootstrap validation