我只想在输入电子邮件时验证电子邮件。
我尝试了以下内容:
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 }
但是这不起作用,因为它会在电子邮件留空时停止显示错误消息。
如何在电子邮件丢失时验证电子邮件是否存在,并且仅在输入电子邮件时验证格式?
答案 0 :(得分:78)
这应该可以解决问题。
validates :email,:presence => {:message => "Your email is used to save your greeting."}, :allow_blank => true,:uniqueness => { :case_sensitive => false }
使用:allow_blank => true
或:allow_nil => true, :if => :email?
编辑:修复拼写错误。
答案 1 :(得分:7)
您可以编写自定义验证功能:
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
或将您的验证器划分为两个单独的验证器,条件为:
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?}
答案 2 :(得分:1)
如果不需要precense,您可以验证格式 :allow_nil =&gt;真