This post originated from an RSS feed registered with Ruby Buzz
by Obie Fernandez.
Original Post: Customizing how Rails validation errors are highlighted
Feed Title: Obie On Rails (Has It Been 9 Years Already?)
Feed URL: http://jroller.com/obie/feed/entries/rss
Feed Description: Obie Fernandez talks about life as a technologist, mostly as ramblings about software development and consulting. Nowadays it's pretty much all about Ruby and Ruby on Rails.
By default, when Rails marks a field in your form that failed a validation check, it does so by wrapping that field in a DIV element, with the class name fieldWithErrors. If you're using Rails scaffolding, this results in the thin red border around the field that we're all familiar with. That behavior is actually customizable, since it is accomplished via a Proc object stored as a configuration property of the ActionView::Base class:
module ActionView
class Base
@@field_error_proc = Proc.new { |html_tag, instance|
"<div class=\"fieldWithErrors\">#{html_tag}</div>"
}
cattr_accessor :field_error_proc
end
...
end
Armed with this knowledge, changing the validation error behavior is as simple as overriding ActionView’s field_error_proc attribute with your own custom Proc. I would suggest doing so either in config/environment.rb or your ApplicationController class.
Here's a simple working example of this technique. I changed the setting so that the input fields with validation errors are prefixed with a red ERR message:
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
%(<div style="color:red">ERR</div>) + html_tag
end
I'm thinking a quick patch may be in order, to give the field_error_proc more valuable arguments. For instance, I would love to know which field is currently being generated, so that I could dynamically add the validation failure message for it.
According to Google, this subject has come up multiple times in the last year or so. For instance, someone complained about field_error_proc in a Rails ticket. However, nothing was done and the ticket was closed because no patch was provided. A DZone snippet suggests how to use regular expressions to add a CSS class name to the html_tag, which is a neat hack, but ugly as all hell. And coincidentally, Pivotal Blabs, (BTW one of my favorite new blog subscriptions) just mentioned it earlier today. In Applying different error display styles, Felix Morio gives us a hack for applying different error field styles, instead of changing the setting globally.