【问题标题】:Need to run the validation one after check another on Rails需要在 Rails 上检查另一个后运行验证
【发布时间】:2017-03-22 05:11:37
【问题描述】:

我已经编写了电子邮件验证 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

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

【问题讨论】:

    标签: ruby-on-rails validation activerecord


    【解决方案1】:

    您可以在此处使用 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? }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-09
      • 1970-01-01
      • 2011-03-05
      • 2011-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多