Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery form validation: Define container for errors

I'm using the jQuery validation plugin, to validate my form. It works (places the error messages, next to the invalid input, which screws up my design), but I'd like to specify the error-container for every input field. I found the errorLabelContainer, but this puts all errors in one container.

Let's say, I have 2 inputs, one with id name and one with firstname. And let's also assume I have 2 error spans, with ids errorName and errorFirstname. How do I tell jQuery to write the validation error for name into the span with the id errorName.

This is my current jQuery:

$("#form").validate({
    errorLabelContainer: "#errors",
        rules: {
            name: {
                required: true
            },
            firstname: {
                required: true
            }
        },
        messages: {
            name: {
                required: "Enter name"
            },
            firstname: {
                required: "Enter firstname"
            }
        }
    })
like image 530
Ahatius Avatar asked May 23 '12 15:05

Ahatius


1 Answers

I think the errorPlacement option suits your needs:

Customize placement of created error labels. First argument: The created error label as a jQuery object. Second argument: The invalid element as a jQuery object.

You can determine the element you want to place the error in based on the invalid element:

$("#form").validate({
    rules: {
        name: {
            required: true
        },
        firstname: {
            required: true
        }
    },
    messages: {
        name: {
            required: "Enter name"
        },
        firstname: {
            required: "Enter firstname"
        }
    },
    errorPlacement: function ($error, $element) {
        var name = $element.attr("name");

        $("#error" + name).append($error);
    }
});

Example: http://jsfiddle.net/R3aEQ/

like image 156
Andrew Whitaker Avatar answered Sep 30 '22 14:09

Andrew Whitaker