How can I get jQuery validation plugin Ketchup to stop an Ajax form submission when validation fails?
- by Marshall Sontag
I'm using Ruby on Rails, Formtastic gem, jQuery and ketchup to validate my form.
I'm submitting the form created by Formtastic inside a modal box using ajax:
<% semantic_form_remote_for @contact_form, :url => '/request/contact' do |f| %>
I have a validation plugin verifying the fields on the form:
$(document).ready(function() {
$("#new_contact_form").ketchup();
});
The problem is that semantic_form_remote_for generates an onSubmit ajax request that the jQuery validation plugins won't prevent, since it's not a normal form submission.
One question on stackoverflow suggests using :condition on the remote form declaration to fire a javascript function, but I can't do that since I'm not using a function, but rather relying on a jQuery handler.
I also tried putting ketchup within a submit event handler:
$(document).ready(function() {
$("#new_contact_form").submit(function() {
$('#new_contact_form').ketchup();
});
});
No luck. Form still submits.
I also tried using the beforeSend option of jQuery.ajax:
$(document).ready(function() {
jQuery.ajax( {
beforeSend: function(){ $('#new_contact_form').ketchup(); }
});
});
Validation fires off, but form is still submitted.
I switched to jQuery Validation plugin just to see if it was due to some limitation in Ketchup. It turns out that Validation has a submitHandler option:
$(document).ready(function() {
$('#new_contact_form').validate({
submitHandler: function(form) {
jQuery.ajax({
data:jQuery.param(jQuery('#new_contact_form').serializeArray()),
dataType:'script',
type:'post',
url:'/request/contact'
});
return false;
}
});
});
This works when I use a regular semantic_form_for instead of semantic_form_remote_for, but alas, I would rather use Ketchup.
Is Ketchup just woefully lacking? Am I forced to use jQuery Validation?