Fixing div.fieldWithErrors in Ruby on Rails

Saturday, May 5th, 2007

Rails’ form helpers are incredibly handy in quickly writing form code, however their error handling code leaves something to be desired. By default, when a field has errors associated with it, the input is wrapped in a div of class “fieldWithErrors”. Unfortunately, this behavior requires you to explicitly change the div to display inline so it doesn’t make the input appear on the next line after the name of the field. I have also had some trouble getting this setting to work in Safari, although that may just be my problem and not Safari’s.

Fortunately, fixing this annoying little gotcha is as easy as adding a single line to the end of your environment.rb file: (I’ve split it into two lines so it will fit on the page, just remove the line break)

ActionView::Base.field_error_proc = Proc.new { |html_tag, instance|
"<span class=\"fieldWithErrors\">#{html_tag}</span>" }

I know many people have already written about this problem, but I wanted to have my own record of it for easy reference 😉

12 Responses

  1. Vinay - May 29th, 2007 at 10:36 pm

    Hey thanks for that man it was really helpful and it worked great. Great job. Keep up the good work.

  2. Vinay - June 1st, 2007 at 2:58 am

    Hey while doing this the “” is replaced by “” any suggestions of getting rid of it? Thanks in advance.:)

  3. Connor - July 7th, 2007 at 3:28 pm

    I’m afraid I’m not really sure what you’re referring to Vinay…

  4. carlivar - August 9th, 2007 at 4:14 pm

    http://dev.rubyonrails.org/ticket/3587

  5. Tony Pitale - October 21st, 2008 at 3:35 pm

    Thank you very much, saved us in a pinch!

  6. Michael - March 15th, 2009 at 11:47 am

    Thank you!

  7. links for 2009-03-21 « Amy G. Dala - March 21st, 2009 at 7:01 am

    […] Ethilien :: Fixing div.fieldWithErrors in Ruby on Rails override a method to change div to span (tags: rails tips) […]

  8. bmsatierf - March 31st, 2009 at 9:24 am

    Thanks =)

  9. Who needs to know - April 8th, 2009 at 6:15 pm

    YOU ARE A GUN!!!! Works great!!!

    Is there a better place to put a bunch of these instead of placing them inside config/environment.rb? For example, creating an rb file under the lib folder?

  10. Sam - August 12th, 2010 at 7:42 am

    Fantastic fix! Thank you.

  11. beyachski - August 31st, 2010 at 3:48 am

    Just create a file Configuration/initializers/action_view.rb and put the code there.

  12. Phil - February 16th, 2011 at 12:24 am

    Doesn’t seem to work with rails 3 (or version 3.0.4.rc1 anyway)

    It’s converting the markup into plain-text using html standards (< >, etc.)