How do you edit Devise error messages?

2019-05-03 10:13发布

问题:

To be clear, I know how to edit the error messages in config/locales/devise.en.yml but I'm referring to styling these type of error messages:

2 errors prohibited this user from being saved:
  • Email can't be blank
  • Password can't be blank

--

All i see is <%= devise_error_messages! %> on the sign-up page, but I don't know how to actually edit the error messages themselves.

In my case the messages appear on the left, and my sign up is centred (which looks odd), I also don't like the red color of the messages and would prefer a different color.

So my question is, how can I style the error message? centre it, and change the color.

Not sure which other controllers or contents to include so as soon as you ask, i'll update the OP with them if need be.

回答1:

See the sources for the devise_error_messages! method at https://github.com/plataformatec/devise/blob/master/app/helpers/devise_helper.rb.

All the errors are inside

<div id="error_explanation"> 

so you can use that fact in your CSS. Inside it uses only basic styling: h2 for the header message, ul for the individual errors. See this SO example for #errorExplanation styling, for example: how to beautify validations in rails. Just don't forget to replace #errorExplanation with #error_explanation in the example.

But your best approach would probably still be to rewrite this method or write and use your own, and there apply all the styling you like.

I'd personally recommend displaying errors next to the fields they belong to. See this SO thread, for example, on how to do that: Rails: Errors close to particular fields in forms.

Another improvement would be switching to simple_form for your forms (and getting errors-next-to-fields for free). See, for example, an excellent Railscast on that: http://railscasts.com/episodes/234-simple-form. There's a more recent revised Railscast, but not sure if you're a Pro subscriber there.