开发者

JQuery Validation errorPlacement Success vs Failure

开发者 https://www.devze.com 2022-12-19 14:22 出处:网络
I\'m using jQuery Validation for a form, and I have to display a checkmark next to the input field (if the entry was correct), and the error message (example:\"please enter at least 4 characters\") be

I'm using jQuery Validation for a form, and I have to display a checkmark next to the input field (if the entry was correct), and the error message (example:"please enter at least 4 characters") below the input field.

I was thinking of doing something like this:

errorPlacement: function(error, element) {

* if the validation is succesful * error.a开发者_运维问答ppendTo($("#checkmark")); * otherwise * error.appendTo($("#error-message")); }

But how can you target a different div destination depending on the type of message you need to display? Or do I have it completely wrong and there's another way to do this?

Thanks!


In the past I've done this by using the validClass option for the valid ones:

$(".selector").validate({
   validClass: "success"
})

success can just be a css class with a checkmark background to the side:

.success {
  background: url(checkmark.png) right no-repeat; /* Say, 16x16px */
  margin-right: 18px;
}


5 months late...hopefully it's still helpful:

jQuery.validate uses the errorPlacement: option for passing the error and element arguments so you can do whatever you want with them...and the function executes every time an error occurs in the user's form. Its counterpart is success: which passes label as an option.

But for ultimate flexibility you don't even have to use "label". Instead you could pass a jQuery object from errorPlacement (based on traversing from the object "element") to the success: option. And success calculates in real time as well.

All somewhat confusing, but here's some generic code...

For your HTML you could put:

<div class="errorparent">
<input type="text" id="username" name="username"/>
<div class="norederrorx errordetails">&nbsp;</div>
</div>

For locating your custom div under your jQuery.validate options:

errorPlacement: function(error, element) {
   var errorcontent=eval(error);
   errorspotholder = element.parents('.errorparent');

And in your success option:

errorspotholder.find('.rederrorx').removeClass('rederrorx').addClass('norederrorx');

If you want to manipulate even more divs...such as a separate valid mark div, you'd simply traverse to a different object from 'errorsotholder' which refers to the containing parent div 'errorparent'

All the best!

Emile


You can search for this expression in jquery.validate.js file :

 this.settings.success( label )

and replace it with :

 this.settings.success( label, element)

This trick repairs jquery-validate as they told in their documentation.

0

精彩评论

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

关注公众号