Reputation: 447
So,
I have been using jQuery Validate for from validation and I have stumbled across something that puzzling me.
I have the form validating properly which is working right but this form is in a modal. Now big deal but when I hit submit, it activates an ajax post, the modal goes away and a DIV on the page updates.
What happens is: The validation works but the ajax still posts.
First: Here is the Javascript validation:
<script>
$(function() {
$.validator.setDefaults({
errorClass: 'help-block',
highlight: function(element) {
$(element)
.closest('.form-group')
.addClass('has-error');
},
unhighlight: function(element) {
$(element)
.closest('.form-group')
.removeClass('has-error');
},
errorPlacement: function (error, element) {
if (element.prop('type') === 'radio') {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
$("#testForm").validate({
rules: {
contractNumber: {
required: true
},
dateFrom: {
required: true,
nowhitespace: true
},
dateTo: {
required: true,
nowhitespace: true
},
contractType: {
required: true
}
},
messages: {
contractNumber: {
required: 'Please enter a contract number.'
}
}
});
});
</script>
<script>
$(document).ready(function() {
$("#testForm").submit(sendForm)
});
function sendForm() {
$.post('index.cfm/candidate/putContract',$("#testForm").serialize(),function(data,status)
{
$('#addContract').modal('hide');
$("#contractView").html(data)
});
return false
}
</script>
This script hides the modal, then posts the results.
What I would like to happen is the validation happen and only pushing when the validation is passed.
http://jsfiddle.net/mwoods98/bh6t2h78/
Here is a fiddle that was setup. It does not post.
Thanks in advance!
Upvotes: 0
Views: 2289
Reputation: 98738
The validation works but the ajax still posts.
That's because your submit
event handler is bypassing the plugin. You will not need to capture the submit
event as that is handled automatically by the plugin.
As per the documentation, the ajax
belongs inside of the plugin's submitHandler
option.
Replaces the default submit. The right place to submit a form via Ajax after it is validated.
submitHandler: function(form) {
// ajax goes here
$.post(....);
return false;
}
DEMO: http://jsfiddle.net/bh6t2h78/2/
In order to get your jsFiddle working properly, I had to comment out your nowhitespace
rule declarations since this method is presently undefined
.
Upvotes: 2