validate email format only if not blank Rails 3

后端 未结 3 1466
庸人自扰
庸人自扰 2020-12-14 00:27

I want to validate the email only if the email has been entered.

I tried the following:

validates :email, :presence => {:message => \"Your emai         


        
3条回答
  •  误落风尘
    2020-12-14 00:45

    You can write custom validation function:

    class Model < ActiveRecord::Base
      validate :check_email
    
      protected
      def check_email
        if email.blank?
          validates :email, :presence => {:message => "Your email is used to save your greeting."}
        else
          validates :email,
            :email => true,
            :uniqueness => { :case_sensitive => false }      
        end
      end
    end
    

    or divide your validator into 2 separate validators with conditions:

    validates :email, 
      :presence => {:message => "Your email is used to save your greeting."}, 
      :if => Proc.new {|c| c.email.blank?}
    
    validates :email, 
      :email => true,
      :uniqueness => { :case_sensitive => false }
      :unless => Proc.new {|c| c.email.blank?}
    

提交回复
热议问题