开发者

How do I stop a custom jQuery.validate.errorPlacement function showing multiple error messages?

I'm using jQuery.validate (with ASP.NET MVC 1.0 and xVal) and trying to override the default error display code so that instead of appending the error span to the element, it appends an error image icon with the error message itself in the image's title/alt attributes.

I'm calling this from the head of my page:

jQuery.validator.setDefaults({
  errorPlacement: function(error, element) {
    var errorTag = '<img src="error.png" title="' + error.html() + '" />';
    var errorImg = $(errorTag);
    errorImg.insertAfter(element);
  }
});

It appears to work fine - right icons in the right pla开发者_运维技巧ce - but then each time validate() is called, it's adding ANOTHER validation icon to the field, so you very quickly end up with dozens of error icons next to each input...

I'm clearly missing some attribute that'll inform the validate plugin that there's already an error for that field, but I can't work out what - I've tried adding an htmlfor=element.Id attribute, I've tried adding the field-validation-error class, but I'm not getting anywhere and now I'm stuck

Thanks,

-D-


You must check whether it exists:

jQuery.validator.setDefaults({
  errorPlacement: function(error, element) {
    var errorTag = '<img src="error.png" id="myTag" title="' + error.html() + '" />';
    var errorImg = $(errorTag);

    if ($('#myTag').length == 0) {
      errorImg.insertAfter(element);
    }
  }
});


The problem is that jQuery.validate uses the error element to tell whether or not the error has already been placed. Your code does not append the element, so for each call it appends your image again.

To see this, do the following:

jQuery.validator.setDefaults({
  errorPlacement: function(error, element) {
    error.insertAfter(element);  // Add the error element

    var errorTag = '<img src="error.png" title="' + error.html() + '" />';
    var errorImg = $(errorTag);
    errorImg.insertAfter(element);
  }
});

Now you will only see the image added once. However, errorPlacement does not get called again if error is present, so your errorTag will not change. Likewise, when the success label is added, the image will not go away automatically.

There may be a way to do this using jQuery.validate methods, but honestly this is just from looking through the code. I am still trying to figure out exactly how all of it is handled.


I have posted a blog post here that explains how to go about doing this from beginning to end for both client and server side validation using jQuery validation. Hope it helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜