简体   繁体   English

如果自定义jQuery验证方法通过,如何返回false?

[英]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. 我创建了自己的验证,该验证是使用json进行的-如果用户电子邮件不是唯一的,则动作将发送响应。 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( don't know how to use ) 第二个变种( 不知道如何使用

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

I want to write a custom jQuery validation method, and here is code : 我想编写一个自定义jQuery验证方法,这是代码

   $.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
        },

Also tried 也尝试过

and it constatly tells me that email is not unique. 同时,它告诉我电子邮件不是唯一的。

I think, I'm constanlty sending true in my custom validation method. 我想,我肯定是在自定义验证方法中发送true。

Where is my error ? 我的错误在哪里?

The method should return true if the form value is valid. 如果表单值有效,则该方法应返回true Your method is returning the whole JSON object, not just data->status . 您的方法将返回整个JSON对象,而不仅仅是data->status And since your checkemail function returns true if the email is found, your method should return !data->status to invert this. 而且,如果找到了电子邮件,由于您的checkemail函数返回true ,因此您的方法应返回!data->status来将其反转。 Finally, your checkemail function doesn't return any object when the email IS unique; 最后,当电子邮件是唯一的时,您的checkemail函数不会返回任何对象。 you need an else clause to return :status => false . 您需要一个else子句来返回: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): 我认为这应该是Ruby-on-Rails脚本(注意:我以前从未做过RoR,我只是将其基于通过谷歌搜索找到的示例中,因此我可能没有完全正确的语法):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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