在Rails 3中自定义Devise错误消息?

我正在使用设计来处理身份validation。 总的来说我喜欢它,但我想自定义错误显示。 现在我的观点中有以下内容。

<div class="field error"> 
"text" %>

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

知道我可以在哪里定制错误消息吗?

谢谢!

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

您可以在模型中覆盖它们。

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

您可以在以下位置配置错误消息: /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 (带截图)。 文章中的“ 自定义错误消息”部分。

如果您想更改设备添加的海关validation的消息,请查看Christian的答案 。

否则,如果要自定义的validation是电子邮件格式等标准validation,则无需删除设计validation并将其替换为您自己的validation。 处理此问题的更好方法是使用Rails指南中列出的默认错误消息优先级,并覆盖特定字段和特定validation的错误消息。

对于此特定问题,您需要在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将按以下顺序搜索要显示validation的消息:

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