Better Flash and Validation Messages

In Rails, there are two common types of messages that we show on a page. Flash messages, which are page-level messages telling the user that something has happened. And validation messages, which are specific to a form that the user filled out (actually, they are specific to a model, but we’ll focus on the user’s point of view).

I rarely see these messages presented in a way that satisfies me. My two big complaints are separation and language.

Separation

I’ve always been bothered at typical Rails apps (including many of ours) that separate flash messages from validation messages, often with completely different styling. In my mind they are slight variations of the same thing: informational messages for the user. They should be shown together, in a consistent location, and with the same styling.

The reason they are typically separate is purely implementation. Flash messages are set in controllers in usually spit out in an application layout file. Validation messages come from model objects and are usually spit out within forms. Rails makes it very easy to do this, and many Rails tutorials promote this separation.

Come together, right now…

Just because it’s easy doesn’t make it right, but I’d much rather have both. Recently I’ve found the message_block plugin that combines flash and validation messages and spits them out in a single div. It’s easy to use and does exactly what it claims. The README is pretty self explanatory, so go check it out.

Language

The validation messages that come packaged with Rails are very convenient. Purely based on the column name and the validation method, Rails can generate an error message that is logically correct. Unfortunately, they are rarely user-friendly.

“User Experience is invalid.”

“Please is not included in the list.”

“Context can’t be blank.”

These are all examples of out-of-the-box validation messages. If you don’t see a problem with them, I probably can’t convince you there is. It’s totally a matter of personal preference.

Now, you’re probably thinking that there is a built-in way to customize validation messages, and you’re half right. The problem is that you can’t customize the full message.

validates_presence_of :city, :message => 'Please enter the city.'

This code will produce the following message:

“City Please enter the city.”

Uh oh. Rails only lets you customize the latter half of the error message. In many cases, and for many developers, this is good enough. But not me. Much like a designer wants control over every pixel, I demand control over every word. Enter custom-err-msg. With this plugin, I can have full control over the message by prepending ’^’.

validates_presence_of :city, :message => '^Please enter the city.'

Problem solved.

These are two plugins I’ll be using in every project from here on out. I think my users will appreciate it.