validation电子邮件格式,如果不是空白Rails 3

我只想在input电子邮件时validation电子邮件。

我尝试了以下内容:

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 } 

但是,这不起作用,因为它阻止电子邮件留空时显示错误消息。

如何validation邮件是否存在,只有在input时validation格式?

这应该做的伎俩。

 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?

编辑:修复错字。

您可以编写自定义validationfunction:

 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 

或者将您的validation器分成两个单独的validation器,并且条件如下:

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

如果不需要precense,你可以validation格式:allow_nil => true