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"
}
}
})
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With