Why is the wrong field value displayed in the error message when using jQuery (remote) validation?

I use the jQuery validation plugin in the same way as Remember The Milk demo .

$("#registrationForm").validate({ rules: { email: { required: true, email: true, remote: '<%=Url.Action(...) %>' }, }, messages: { email: { required: "Please enter an email address", email: "Please enter a valid email address", remote: jQuery.format("{0} is already in use") } }); 

The first time an invalid email address is sent (for example, bob@mail.com ), the error message is as expected. However, if I then enter a still invalid email address (for example, sue@mail.com ), the verification plugin still shows that " bob@mail.com already in use."

I Url.Action track of the parameters that reach the controller specified in the Url.Action call, and they are definitely correct (ie " sue@mail.com " is sent as an email address when this is what is entered in the field).

Does anyone else encounter this or similar issue using jQuery validation plugin?

0
source share
2 answers

The username field in the Remember the Milk demo does not work the same way (when entering the usernames "Peter" and "George"), so you probably found an error in the plugin.

+1
source

More than two years later, and the error still does not seem to be fixed, so here is what I found:

The problem is the remote function:

 remote: function(value, element, param) { if ( this.optional(element) ) return "dependency-mismatch"; var previous = this.previousValue(element); if (!this.settings.messages[element.name] ) this.settings.messages[element.name] = {}; previous.originalMessage = this.settings.messages[element.name].remote; this.settings.messages[element.name].remote = previous.message; // snip more code... } 

The problem is that in the 2nd and subsequent evaluations of this function, messages[element.name].remote contains a specific (text) error message, and the actual original message is lost forever when the previous.originalMessage overwritten after that.

I managed to solve the problem by adding a check before this line:

 if (!previous.originalMessage) previous.originalMessage = this.settings.messages[element.name].remote; 

I’m not sure if this is really the right solution, but it works - validation errors now re-apply the format function with every validation failure.

+2
source

Source: https://habr.com/ru/post/1383417/


All Articles