Does jQuery validation plugin: valid () not work with remote validation?

I started with this amazing tutorial , but wanted to do keyboard validation and put my errors somewhere else. Remote verification displays its own error message at appropriate times, making me think that I worked. But if I ask if the field with remote validation really is, it says no, in fact, it does not.

In application.js, I have this ...

$("#new_user").validate({ rules: { "user[login]": {required: true, minlength: 3, remote: "/live_validations/check_login"}, }, messages: { "user[login]": {required: " ", minlength: " ", remote: " "}, } }); $("#user_login").keyup(function(){ if($(this).valid()){ $(this).siblings(".feedback").html("0"); }else{ $(this).siblings(".feedback").html("1"); } }) 

And then this is in the rails application ...

 def check_login @user = User.find_by_login(params[:user][:login]) respond_to do |format| format.json { render :json => @user ? "false" : "true" } end end 

I think that my problem may have everything related to this ticket in jQuery, and tried to implement this code, but being new to jQuery, it is all a little over my head. When I say a bit, I mean the way.

Any ideas to fix this, or a new way to look at it, would be of great help.

+4
source share
1 answer

When you call $ (this) .valid (), it ends the call to / live _validations / check_login asynchronously. The valid () method returns immediately, without waiting for check_login to complete, and since it does not know what the result will be, it simply returns false.

Looking at the code of the Validation plugin, I think that instead you should call the element () method, which will return true, false or undefined - it will return undefined during an asynchronous call, while valid () returns true or false. When you get undefined, you know that you still need to wait for an answer to your server.

I think you can do something like this (untested, but with what to play). Note that repeated calls to element () will not trigger new Ajax calls; they only do this if the value has changed. So there is no harm.

 function checkResult() { var valid = $(formSelector).validate().element('#user_login'); // Will not launch a new request if the value hasn't changed if (typeof valid == 'undefined') { setTimeout("checkResult()", 100); } else { // it done! if(valid){ $(this).siblings(".feedback").html("0"); }else{ $(this).siblings(".feedback").html("1"); } } }; $("#user_login").keyup(function(){ $(formSelector).validate().element('#user_login'); // launches the remote request setTimeout("checkResult()", 100); }) 
+6
source

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


All Articles