jQuery Validation Plugin: How can I force validation on previously valid fields?

我的未来我决定 提交于 2019-12-20 12:32:53

问题


I'm using jQuery Validation plugin to validate a form. Do you know how to force revalidation on previously successful fields?

I have tried the .form function using the following check (this is performed after the user clicks 'submit'):

if ($('#form1').validate().form()==false)
{
    formValid = false;
}

However, it appears that the code above does not retry validation so fields that are already successfully validated (ie have tick next to them) are not checked again.

The reason for wanting to retry revalidation on previously successful fields is that they rely on remote validation, and the outcome (success or failure) can change between the user leaving the field, and clicking submit. (This applies to a 'username' field).

In case it affects the answer I have multiple forms to validate (for simplicity, in the code snippet above I refer to '#form1' only).

Thanks in advance for any advice,

Rob


回答1:


The state of validation for remote fields is stored via $.data() with the element you want to validate, so you could use .removeData() to clear that out...so it's forced to revalidate:

$("#form1 :input").removeData("previousValue");
//now call .valid()

This forces the check if the value has changed (we need to re-validate) to be true:

//This code is in the validation plugin for remote:
var previous = this.previousValue(element);
if (previous.old !== value) { //this is normally false, since it hasn't changed

If there are only specific fields that need re-validating, like you said username, you may want to narrow the $("#form1 :input") selector to only the fields you want, to make it a bit more efficient.




回答2:


I came upon this answer when I was looking into using jQuery remote unobtrusive validation. It wasn't the best documented topic in the world and also it wasn't without quirks. So much so that I ended up writing a blog post about what I learned. Link here in case helpful:

http://icanmakethiswork.blogspot.com/2012/03/jquery-unobtrusive-remote-validation.html



来源:https://stackoverflow.com/questions/3797455/jquery-validation-plugin-how-can-i-force-validation-on-previously-valid-fields

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