电子邮件空白或空白时的活动记录模型验证

时间:2014-04-03 05:23:03

标签: ruby-on-rails activerecord model-validation

sign up页面中,我想验证用户的电子邮件,如果用户输入无效的电子邮件或电子邮箱文本框留空并希望显示错误消息Enter your email address

我的User型号:

VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
            uniqueness:  { case_sensitive: false }

使用上述正则表达式,我正在验证电子邮件但不知道如何添加和显示错误消息。

请帮助我。感谢。

2 个答案:

答案 0 :(得分:2)

试试吧:

VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, 
          :presence => {:message => "Enter your email address!" },
          :format => { :with => VALID_EMAIL_REGEX, :message => "Enter a valid Email address !"}
          :uniqueness => {:case_sensitive => false, :message => "Email already exists!"}

要查看这些错误,请使用Rails(<%= f.error_messages %>)提供的默认错误帮助程序。

<%= form_for @user, :url => {:controller=>"users", :action => "sign_up" } do |f| %>  
   <%= f.error_messages %> 
   ---form fields and contents --
<%end%>

希望有所帮助:)

答案 1 :(得分:0)

对于错误消息,您只需添加message: 'your message'就这样做。

如果要提供单独的错误消息,则必须拆分验证。

validates :email, presence: true, :format=> { :with=> VALID_EMAIL_REGEX , :message=> 'Enter your Email Address' }

validates :email, uniqueness: {:case_sensitive => false, :message => 'Please provide a valid Email' }