根据另一个字段的存在有条件地要求和验证电子邮件

时间:2017-04-27 06:43:34

标签: ruby-on-rails ruby

我允许电子邮件有时是可选的,具体取决于是否有phone字段。如果存在 - 不验证存在,如果没有 - 验证它。这是代码:

# model.rb
validates :email, length: {maximum: 255},
        uniqueness: {case_sensitive: false},
        email: true

validates_presence_of :email, unless: Proc.new {|user| user.phone? }

问题在于,如果用户提交空email字段,则Email has already been takenEmail is not an email会出错。

我还有email_validator.rb

class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attr_name, value)
    unless value =~ MY_EMAIL_REGEX
      record.errors.add(attr_name, 'is not an email')
    end
  end
end

我想:

  • 仅在输入
  • 中有值时验证电子邮件格式
  • 当不需要电子邮件时(例如,手机存在),允许空白(或)空白

1 个答案:

答案 0 :(得分:1)

您在Proc的一次验证中使用了email,但在其他验证中没有使用{},

validates :email, length: {maximum: 255},
        uniqueness: {case_sensitive: false},
        allow_blank: true, # This option will let validation pass if the attribute's value is blank?, like nil or an empty string
        email: true, unless: Proc.new {|user| user.phone? }

validates_presence_of :email, unless: Proc.new {|user| user.phone? }

您可以合并这两个验证:

validates :email, length: {maximum: 255},
           uniqueness: {case_sensitive: false},
           presence: true,
           allow_blank: true, # This option will let validation pass if the attribute's value is blank?, like nil or an empty string  
           email: true, unless: Proc.new {|user| user.phone? }