validate email format only if not blank Rails 3

Solution 1:

This should do the trick.

validates :email,:presence => {:message => "Your email is used to save your greeting."}, :allow_blank => true,:uniqueness => { :case_sensitive => false } 

Use:allow_blank => true or :allow_nil => true, :if => :email?

edit: fix typo.

Solution 2:

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

Solution 3:

you can validate format if no precense required :allow_nil => true