8th
JUL

Validate multiple forms with same class with jQuery Validator

Posted by Lee under Programming, jQuery

Ran into a very frustrating problem today whilst developing a dynamic form generator for Breeze CMS - we needed the jQuery Validator plugin (worth the download!) to be able to validate multiple forms (that had the same content) but the fun part was that we don’t know how many forms there would be. I thought it would be as simple as setting a common class for the forms and attaching the validate function to them but it wasn’t.

Below is a sample of the code I originally tried

$('.addFieldForm').validate({
event: "keyup",
rules: {
field_name: "required"
},
etc. etc.

It would only end up submiting the first form using the above code. The solution thankfully wasn’t too complex - just took a while to think of the solution! What you need to do is use the ‘jQuery.validator.setDefaults‘ option and set the validation details you are going to use for the forms. Then the big secret on how to attach to each form is below:

$('.addFieldForm').each( function(){
$(this).validate();
});

Nice and simple solution!

Reader's Comments

Leave a Reply

(required)
(will not be published) (required)

The Lab is the web development blog for PX Webdesign that covers many subjects from PHP, CSS, jQuery, CodeIgniter, Design and XHTML / HTML