2017-04-27 22 views
1

根據是否存在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

您已使用Procemail一個驗證,但不是在其他驗證,在兩者都使用:

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? } 
+0

謝謝!部分問題是允許使用空白電子郵件,在這種情況下無效,而沒有電子郵件註冊的第二位用戶將獲得'index_users_on_email''鍵的'重複條目' – abpetkov

+0

@abpetkov:更新了我的答案,有關allow_blank的更多信息:http://guides.rubyonrails.org/active_record_validations.html#allow-blank –

+0

即使允許nil和空白,我也會得到'Duplicate entry'錯誤。 – abpetkov