Jquery validation error placement outside form with absolute positing of error message

Venu picture Venu · Jul 1, 2011 · Viewed 9.5k times · Source

I am trying to place the error message elements outside the FORM element which is being validated. I would like to place all the error labels at the bottom of the DOM and change them to absolute position.

errorPlacement: function(error, element) {

                if (element.hasClass('section')){
                    element = element.parent();
                }
                offset = element.offset();
                $('#val_errors').append(error);
                error.addClass('val-message');  // add a class to the wrapper
                error.css({'position':'absolute','z-index':'10'});
                error.css('left', offset.left + element.outerWidth());
                error.css('top', offset.top);

            }

I have checked other post which is very similar to my question, But there is no solution. JQ validation plugin - error labels ( errorPlacement ) outside the form, is it possible?

Please help me out

Thanks Venu

Answer

Brian Hoover picture Brian Hoover · Jul 1, 2011

Venu, This code works for me:

errorPlacement: function(error, element) {
    error.appendTo($("div#errorContainer"));
}

Where you would already have the errorContainer already set to where you wanted it to be. You could also set the errorContainer on the fly using normal jQuery/CSS functions:

errorPlacement: function(error, element) {
    error.appendTo($("div#errorContainer"));
    $("div#errorContainer").css({'position':'absolute','z-index':'10'});
    $("div#errorContainer").css('left', offset.left + element.outerWidth());
    $("div#errorContainer").css('top', offset.top);

}

It appears that you would then have to create a new div error container on the fly each time, since you are floating based on the element that threw the error, and multiple errors could be thrown.

So, the code to create new floating divs would look like:

 errorPlacement: function(error, element) {
    $('body').append('<div id="error' + element.attr("id") + '" class="errorContainer"></div>');
    error.appendTo($('div#error' + element.attr("id")));
    offset = element.offset();

    $('div#error' + element.attr("id")).css({'position':'absolute','z-index':'10'});
    $('div#error' + element.attr("id")).css('left', offset.left + element.outerWidth());
    $('div#error' + element.attr("id")).css('top', offset.top);

}

Then to clear messages, you could have something like:

$("input").change(function() {
    $('div#error' + $(this).attr("id")).remove();
})