Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validate email format only if not blank Rails 3

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

I tried the following:

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

However this does not work as it stops error messages from showing when the email is left blank.

How can I validate the presence of the email when it is missing and ONLY validate the format when it has been entered?

like image 963
chell Avatar asked Jul 04 '11 05:07

chell


People also ask

How to validate email format in Rails?

Email_validator gem validation For example, a simple one to use is the email_validator gem. It's that simple! This gem provides a simple email validation technique by checking if there's an at-sign (@) with some characters before or after it. If the sign is present, it returns, true; otherwise, it returns false.

How to validate email in Ruby?

The first validation method, validates_presence_of, checks whether the email field is empty. The second method, validates_format_of, compares the email with the particular regular expression. The advantage here is that the same regular expression can be used to validate emails in different classes and methods.

What are validations in Ruby on Rails?

Validations are used to ensure that only valid data is saved into your database. For example, it may be important to your application to ensure that every user provides a valid email address and mailing address. Model-level validations are the best way to ensure that only valid data is saved into your database.


2 Answers

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.

like image 98
Abhaya Avatar answered Oct 31 '22 05:10

Abhaya


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?}
like image 7
Hck Avatar answered Oct 31 '22 03:10

Hck