Proper error messages on rails

In order to have proper validation error messages on the web page I want to specify what the message will look like. Problem is that if you set validation message in your Person model like this:

validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :message => ‘invalid e-mail address’

you get on you page error message like this:

1 error prohibited this person from being saved

There were problems with the following fields:

‘Email invalid e-mail address’

but customer wants something more human like., for example:

Oh dear there were problem

That doesn’t look like a valid e-mail address. Please try again.

I found a solution and here is how to do that. First we change the Header error message and delete the submessage.

In your view where you are displaying errors use proper options for error_messages_for

error_messages_for(:person, :header_message => “Oh dear there were problem”, :message => “”)

Than the interesting part, error messages are in this format [attribute_name, message] but we need only the message part so without any hacking or parsing we can specify format of the message directly:

validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :message => :”email.format”

The part :”email.format” says that you have specified message text at your i18n file (usually config/locale/en.yml) .

en:
  activerecord:
    errors:
      full_messages:
        email:
          format: "That doesn't look like a valid e-mail address. Please try again."

And that’s it :) Feel free to comment.