Speed Bumps with Validation in Rails

I'm trying to figure out how to implement some basic human-readable validation in Rails, and I'm hitting some speed bumps. First, the built-in error_messages_for() is pretty good, but the header isn't very human:

"1 error prohibited this event from being saved"


First question is, how do I customize this header? For example, I'd like to avoid words like "prohibited" and "error," and I'd like to either customize or hide the name of the type of thing being validated. I've been doing all sorts of searching and I haven't found any answers on this.

For the actual message, I'd like something like this:

First name, Last name, City, State and Zipcode are all required
Phone number must be a number


I've tried all sorts of things to achieve this, including traversing the errors array and even attempting to create a custom validation keyword. I couldn't really get the custom keyword stuff to work at all, as there's not much documentation beyond this.

As it stands, I'm stuck with output like this:

First name can't be blank, Last name can't be blank, City can't be blank, State can't be blank, Zipcode can't be blank


Which looks ridiculous. :)

Does everyone just do one giant validate method?
Design Element
Speed Bumps with Validation in Rails
Posted Oct 23, 2005 — 3 comments below




 

Justin Williams — Oct 23, 05 453

Rather than separating them by a comma, I put each on in its own bullet point. That makes it much more readable I think.

Mr eel — Oct 23, 05 454

The error_messages_for() method is limited, in that it can only handle error mesages for one object and no you cannot customise the display. You can check out the API reference here.

Rather than wrestle with it, I've written my own helper method for displaying errors. It handles error messages for multiple objects. A bit limited now, but in the future I hope to expand it to let you customise it a bit more.

As for grouping similar errors together... I think this might be a bit tricky, but it's got me thinking now.

Benko — Oct 24, 05 455

What I do in my "models" is setting the "message" for every validation, like this:

validates_presence_of :title, :on => :save, :message => "Please specify the title of your post"

No idea how to group validations into one message, I display them one by one in a list as Justin suggests.




 

Comments Temporarily Disabled

I had to temporarily disable comments due to spam. I'll re-enable them soon.





Copyright © Scott Stevenson 2004-2015