2011-04-30 63 views
9

我正在使用设计来处理验证。总的来说,我喜欢它,但我想定制一些错误显示。在我看来,我现在有以下几点。定制在Rails 3中设计错误消息?

<div class="field <% if resource.errors[:email].present? %>error<% end %>"> 
    <%= f.label :email, "Email:" %><br /> 
    <% if resource.errors[:email].present? %> 
    <ul> 
     <% resource.errors[:email].each do |msg| %> 
     <li><%= msg %></li> 
     <% end %> 
    </ul> 
    <% end %> 
    <%= f.text_field :email, :class => "text" %> 
</div> 

但是,当电子邮件出现问题时,显示的消息如下:is invalid。这不是非常用户友好的,但我无法找到此消息的设置。它似乎没有在devise.en.yml中,但也许我忽略了一些东西。

任何想法,我可以自定义错误消息?

谢谢!

回答

8

这些验证都在validations模块中定义,并使用默认的Rails错误消息。

您可以在模型中重写这些。

validates_format_of :email, :with=>email_regexp, :allow_blank => true, :message=>"new error message here" 
+2

谢谢!同样值得注意的是,为了使其发挥作用,您需要从模型中删除':validatable'并将所有验证转移到模型中。 – 2011-04-30 12:13:29

+1

完成它,而不必重写Devise验证的Rails方式是[这里](http://stackoverflow.com/a/18578028/1964165) – akhanubis 2013-09-02 17:23:55

28

您可以配置在语言环境中的错误信息文件在:/config/locales/devise.en.yml

里面应该有类似下面的代码,哪些是你可以轻松地修改您的喜欢:

en: 
    errors: 
    messages: 
     not_found: "not found" 
     already_confirmed: "was already confirmed" 
     not_locked: "was not locked" 

    devise: 
    failure: 
     unauthenticated: 'You need to sign in or sign up before continuing.' 
     unconfirmed: 'You have to confirm your account before continuing.' 
     locked: 'Your account is locked.' 
     invalid: 'OH NOES! ERROR IN TEH EMAIL!' 
     invalid_token: 'Invalid authentication token.' 
     timeout: 'Your session expired, please sign in again to continue.' 
     inactive: 'Your account was not activated yet.' 
    sessions: 
     signed_in: 'Signed in successfully.' 
     signed_out: 'Signed out successfully.' 

对于更详细的解释,看看这个url(有截图)。本文中的自定义错误消息部分。

+1

感谢您的建议。正如我在我原来的问题中指出的,我看到的错误消息不在locales文件中。不过,RobZolkos的回答让我走了。谢谢! – 2011-04-30 12:15:26

9

如果要更改设备添加的海关验证信息,请选择Christian's answer。否则,如果您要定制的验证是电子邮件格式等标准验证,则不需要删除Devise验证并用您自己的验证替换它们。处理此问题的更好方法是使用Rails guides中列出的默认错误消息优先级,并覆盖特定字段和特定验证的错误消息。

对于这个特定的问题,您需要在config/locales/en.yml添加,以改变is invalid带有自定义消息的电子邮件错误,关键是activerecord.errors.models.user.attributes.email.invalid(其中user是模型的名称):

en: 
    activerecord: 
    errors: 
     models: 
     user: 
      attributes: 
      email: 
       invalid: "custom invalid message" 

Rails将按以下顺序搜索显示验证消息:

activerecord.errors.models.[model_name].attributes.[attribute_name] 
activerecord.errors.models.[model_name] 
activerecord.errors.messages 
errors.attributes.[attribute_name] 
errors.messages