在Rails

时间:2017-03-22 05:11:37

标签: ruby-on-rails validation activerecord

我已经编写了电子邮件验证Rails ActiveRecord它的工作正常,这是我的电子邮件验证代码

def email_validation

validates :email,
            :presence
validates_format_of :email,
                    with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i,
                    message: 'Invalid email address'
validates_uniqueness_of :email,
                        case_sensitive: false,
                        message: 'Email has already been entered'
end

问题是当我输入空电子邮件地址时,我收到了以下响应消息。

{
  "status": "E1000",
  "description": {
    "email": [
      "can't be blank",
      "Invalid email address"
    ]
  }
}

此处的回复消息显示“不能为空”和“无效的电子邮件地址”。我需要的是......我需要验证第一个条件,如果它成功,那么我只验证第二个条件。如果成功,那么我验证第三个。

我试过

if email.presence? 
     #condition 1
else 
    #condition 2
    #condition 3
end

但它不起作用。如何以顺序检查方式执行此操作

1 个答案:

答案 0 :(得分:2)

您可以在此处使用Proc:

validates :email, :presence
validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, message: 'Invalid email address', :if => Proc.new { |o| o.errors.empty? }
validates_uniqueness_of :email, case_sensitive: false, message: 'Email has already been entered', :if => Proc.new { |o| o.errors.empty? }