JQuery Validation errorPlacement Success vs Failure

落花浮王杯 提交于 2019-12-24 07:52:07

问题


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.appendTo($("#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!


回答1:


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;
}



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/2236243/jquery-validation-errorplacement-success-vs-failure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!