简体   繁体   中英

How to return false if custom jQuery validation method is passing?

I created own validation, which is made using json - action is sending response if user email is not unique. Here is action:

def checkemail
 respond_to do |format|
  format.jsonr do
    if User.where(email: params[:email]).exists? 
      render :json => {
            :status  => :false,
            }.to_json
    else
      render :json => {
            :status  => :true,
            }.to_json
     end
    end
  end
end

Second variant( )

   def checkemail
   render :nothing
    if User.where(email: params[:email]).exists? 
      return false
    else
      true
    end
  end

:

   $.validator.addMethod("uniqueness", function(value) {
    $.getJSON('http://127.0.0.1:3000/checkemail.jsonr', { email: $('#email').val() }, function(data)  {
       return data.status
    });
}, 'Your email is not unique');
 .....
 "user[email]":{         //here is no error in name
    uniqueness: true
        },

and it constatly tells me that email is not unique.

I think, I'm constanlty sending true in my custom validation method.

The method should return true if the form value is valid. Your method is returning the whole JSON object, not just data->status . And since your checkemail function returns true if the email is found, your method should return !data->status to invert this. Finally, your checkemail function doesn't return any object when the email IS unique; you need an else clause to return :status => false .

Instead of a custom method, use the built-in remote validation:

"user[email]" {
  remote: {
    url: "http://127.0.0.1:3000/checkemail.jsonr",
    type: "get",
    data: {
      email: function() { return $("#email").val(); }
    }
  }
}

I think this should be the Ruby-on-Rails script (note: I've never done RoR before, I'm just basing it on examples I found by googling, so I may not have gotten the syntax quite right):

def checkemail
 respond_to do |format|
  format.json do
    if User.where(email: params[:email]).exists? 
      render :json => false
    else
      render :json => true
    end
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM