【问题标题】:How to return false if custom jQuery validation method is passing?如果自定义 jQuery 验证方法通过,如何返回 false?
【发布时间】:2012-09-13 07:06:32
【问题描述】:

我创建了自己的验证,它是使用 json 进行的 - 如果用户电子邮件不是唯一的,则操作发送响应。这是行动:

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

第二个变种(不知道怎么用)

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

我想写一个自定义的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
        },

也试过了

它不断地告诉我电子邮件不是唯一的。

我想,我在我的自定义验证方法中不断发送 true。

我的错误在哪里?

【问题讨论】:

    标签: jquery ruby-on-rails json jquery-validate


    【解决方案1】:

    如果表单值有效,该方法应返回true。您的方法返回整个 JSON 对象,而不仅仅是 data->status。由于如果找到电子邮件,您的 checkemail 函数将返回 true,因此您的方法应返回 !data->status 以反转它。最后,当电子邮件唯一时,您的 checkemail 函数不会返回任何对象;你需要一个else 子句来返回:status => false。

    使用内置的远程验证代替自定义方法:

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

    我认为这应该是 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
    

    【讨论】:

    • 谢谢 Barmar,我会编辑问题,你会再次告诉我我错过了什么,好吗?
    • 更新问题。还是一样。
    • 问题是$.getJSON是异步的。它立即返回,并在 AJAX 调用返回时调用回调函数。你为什么不重写你的 checkemail 函数只返回 true 或 false,然后你可以使用内置的远程验证来处理这个问题?
    • 类似的东西(再看一遍)?但现在我不应该使用 getJson 是吗?如何实施?如果我不使用 json,如何动态传递参数?
    • 你还需要在服务端渲染JSON。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-20
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多