views:

65

answers:

2

I am currently working with the jQuery validation plugin, and I want to show only one error-message before the form itself. Right now the validation shows all the error-messages on top of each others as they stack up, as you can see in my live example:

http://timkjaerlange.com/foobar/stack-stuff/validate-test.html

This is my current jQuery:

$(document).ready(function() {
  $("form").validate({
    rules: { // bunch of rules here, left out to keep it simple },
    messages: { // messages goes here },
    errorElement: 'div',
    errorClass: 'error',
    errorPlacement: function(error, element) {
      error.insertBefore('form'); // this is what I've got
    }
  });
});

But I only want to show the latest error-message, so to replace the previous error with the next one I want to do something like this instead:

    errorPlacement: function(error, element) {
      $('div').replaceWith(error); // trying to replace the prev error
    }

Anybody know how to this? Is this the best way to show only one error-message?

Any help is highly appreciated.

+1  A: 

Sounds like a viable solution but replaceWith would replace the div with the error label and would fail on all subsequent calls as no div is found.

This should do it

$('div').empty().append(error);

Just a side note. This will probably lead to unwanted behavior. Just think what happens when e.g. 3 fields are invalid. 3 error labels are generated and you place them inside this even (overwriting each other). Thus only the last label is visible. But what happens when the user fixes the error shown? No error will be shown although 2 fields still are invalid.

jitter
Thanks for a swift reply, this forum is the best! :)I see what you mean, initially I used CSS to hide the labels as they stacked up, but it was a hack and not pretty at all. I guess what I want is to show the latest error-message and then when the affected input field is valid I want to show the previous error-message in the stack - if it's corresponding input-field is still invalid.Btw: tried to implement your solution, but it didn't work, live example here:http://timkjaerlange.com/foobar/stack-stuff/validate-test2.html
timkl
A: 

Deal it as an presentation issue and just hide non-first error elements using CSS ;)

jholster
This is what I did initially but I ran into some weird problems. Did a CSS-version of my example:http://timkjaerlange.com/foobar/stack-stuff/validate-test3.htmlIt works, but it's sort of a cheating to do it in CSS, I recon ;)
timkl
The weird problem being that if I fill out the form correctly, and then edit the input fields to be invalid and then back to valid again, then the last error-message is still being shown.
timkl