BarryWalsh
BarryWalsh

Reputation: 1340

jQuery Validation plugin - multiple forms on page - only validate the submitted one

I'm using the great jQuery Validation plugin - http://jqueryvalidation.org/ and need to use a class- to validate a form.

The thing is there could be more than one form on a page with and they would have that same class. When I try to submit one form the plugin validates both forms instead of just the one being submitted.

Does anyone know a work around for this? I've tried adding a randomly generated ID to each form and grabbing that in a submit event but the validation plugin fails silently when I try it.

Cheers!

Update:

//validate and submit form
jQuery('.js-booking-form').validate({
  submitHandler: function(form) {
    //Submit Booking Request via AJAX
  }
});

and sample HTML both forms are pretty much identical so here's shortened version:

<form class="js-nudge-booking-form nudge-vertical-booking-form" data-ajaxurl="http://localhost/site/ajax/">
 <input type="text" placeholder="Name" name="client-name">
 <input type="email" placeholder="Email" name="email">
 <input type="submit" value="Submit">
</form>

Upvotes: 1

Views: 698

Answers (2)

BarryWalsh
BarryWalsh

Reputation: 1340

Got it sorted - Using each to loop through the forms and referencing the form to validate through the "this" keyword works.

Found the solution here: http://www.ozonesolutions.com/programming/2012/02/jquery-validation-plugin-with-multiple-forms/ I can't really figure out why it works as I would think that it would be telling the plugin to validate each form.

Upvotes: 1

user1784014
user1784014

Reputation: 244

I don't quite understand why you HAVE to use Class name to validate. A quick and simple solution would be to have separate ID for each form and reference the form by ID

<form id="form1" class="yourclass">...</form>
<form id="form2" class="yourclass">...</form>

To validate a specific form:

$('#form1').validate({...});

By referencing your form by class, you will always get 2 form objects returned because both form have the same class name. And Hence your current dilemma. Now you can get around that, but that would involve either modify jquery.validate code itself or validate handler.

Upvotes: 0

Related Questions