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?
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.
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.
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.
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.
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?}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With