views:

387

answers:

1

I have a form that uses the validation plugin, but I need to validate a separate part of the form using slightly different criteria - most of the fields place the error in the next table cell, but for one field I need the error placed somewhere else.

This is the validate function for the main form fields:

jQuery("#form2").validate({
    rules: {
        street: {
            required: true,
            minlength: 5
        },
        city: {
            required: true,
            minlength: 3
        },
        state: {
            required: true
        },
        zip: {
            required: true,
            minlength: 5
        }
    },
    messages: {
        street: {
            required: "Please enter your address",
            minlength: "Address is too short"
        },
        city: {
            required: "Please enter your town/city",
            minlength: "Town/City is too short"
        },
        state: {
            required: "Please enter your county"
        },
        zip: { 
            required: "Please enter your postcode",
            minlength: "Postcode is too short"
        }
    },
    errorPlacement: function(error, element) {
            error.appendTo(element.parent("td").next("td"));
    }
}); // end validate

Basically I would also like to validate this fieldset separately, so a different value can be used for errorPlacement:

    jQuery("#elecfields").validate({
    rules: {
        sup1: {
            minlength: 2
        }
    },
    messages: {
        sup1: {
            minlength: "must be 2 digits"
        }
    },
    errorPlacement: function(error, element)
    {
        // different error placement is needed here
    }

}); // end elecfields validate

elecfields is a fieldset inside form2 - but this doesn't seem to work.

It seems that the errorPlacement must apply to all fields in the form, but I just have that one field that needs the error places somewhere else. Any ideas for how this can be achieved? Any help is very much appreciated.

A: 

You're right. The errorPlacement handler does apply to the entire form, but you can also have logic in there to handle the error differently in certain situations. For instance, you could look at the element property direclty and watch for the items in question, or you could filter them based upon a common parent - in your case the fieldset. Example:

$("#form").validate({
    /* */
    errorPlacement: function(error, element)
    {
        if( element.closest("#subFieldSet").length ) {
            /* special handling */
        } else {
            /* generic handling */
            error.insertAfter(element);
        }
    }
});
BBonifield