Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 979
Rob Avatar asked Sep 26 '10 10:09

Rob


2 Answers

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.

like image 188
Nick Craver Avatar answered Sep 18 '22 07:09

Nick Craver


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

like image 21
John Reilly Avatar answered Sep 20 '22 07:09

John Reilly