jdepypere
jdepypere

Reputation: 3553

jQuery Validate plugin - get two wrappers around error label

I'm having some trouble getting my JQuery Validation up to where I want. My errors display in a sidebox with an arrow. This can be achieved with a single 'wrapper'.

$('#loginform').validate({
    errorPlacement: function(label, element) {
        label.addClass('arrow');
        label.insertAfter(element);
    },
    wrapper: 'span'
});

The issue is that unfortunately I have a box around my input fields, so the error should be placed over that border of that box. To do this, I need two wrappers. So my error should look like this:

<span class='errorContainer'>
    <span class='arrow'>
        <span class='error'>This is the actual error message.</span>
    </span>
</span>

The current code gives me only this:

<span class='arrow'>
    <span class='error'>This is the actual error message.</span>
</span>

Upvotes: 1

Views: 3066

Answers (2)

Sparky
Sparky

Reputation: 98738

There is nothing wrong with the accepted answer, but I wanted to show a more efficient way to achieve the same desired DOM structure.

Instead of inserting an empty container, finding the inside element, and then appending the error... the following is less verbose and more direct; it just wraps the label with the desired container.

errorPlacement: function (error, element) {
    error.insertAfter(element)
    .wrap('<span class="errorContainer"><span class="arrow"></span></span>');
},

This has the advantage of taking the plugin's default errorPlacement callback...

error.insertAfter(element)

...and then just chaining the jQuery .wrap() method to the end...

.wrap('<span class="errorContainer"><span class="arrow"></span></span>')

Working Demo: http://jsfiddle.net/2ZaLB/

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388316

You can use

errorPlacement: function(label, element) {
    $('<span class="errorContainer"><span class="arrow"></span></span>').insertAfter(element).find('.arrow').append(label)
}

Demo: Fiddle

Upvotes: 4

Related Questions