Skip to content

Customize i18n of authentication keys like 'email' in auth failure messages

Tom Smyth edited this page Dec 1, 2018 · 3 revisions

You may notice that by default your auth failure message look something like "Invalid Email or password."

Why is "Email" capitalized? Because Devise is using User.human_attribute_name(:email), which tends to be capitalized.

You can control i18n of parameters to authentication failure messages by doing something like this:

In app/models/custom_devise_failure_app.rb:

# Overriding the i18n_options method in the Devise FailureApp so that we can have control
# over how the `authentication_keys` parameter to the messages under devise.failure is translated.
# By default the `human_attribute_name` of the attribute is used, but those are typically capitalized,
# while the messages call for a lowercase value.
# This custom failure app must be activated in the config/initializers/devise.rb file.
class CustomDeviseFailureApp < Devise::FailureApp
  def i18n_options(options)
    options.merge(authentication_keys: I18n.t("devise.authentication_keys.email"))
  end
end

and then in config/initializers/devise.rb:

  config.warden do |manager|
    manager.failure_app = CustomDeviseFailureApp
  end

and then in your devise.yml file:

  devise:
    ...
    authentication_keys:
      email: "email"

Ideally Devise would support an optional authentication_keys key in the YML file out of the box, so you could have control over these params without a custom failure app, but this works right now and is not particularly hacky. There is support for this method in the test suite even, see here.

Clone this wiki locally