2017-03-22 47 views
0

我寫電子郵件驗證Rails的ActiveRecord的它工作正常,這裏是我的電子郵件驗證碼需要運行驗證一個檢查另一on Rails的後

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 

,但它不工作。如何按順序檢查方式執行此

回答

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? } 
相關問題