Fixing fieldWithErrors behavior

posted on 30 Jun 2009 | Rails

Dealing with errors in Rails forms can be a hard task. When a form field has errors, ActionView wraps the input in a div of class "fieldWithErrors". The result is something like this

<p><div class="fieldWithErrors"><input id="user_name" name="user[name]" type="text" value="" /></div></p>

A div inside a paragraph ?¿?¿? This behavoir can be very annoying and isn't XHTML compliant. A simple solution is add this line at the end of environemnt.rb or in a file under lib dir:

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

This is the result

<p><span class="fieldWithErrors"><input id="user_name" name="user[name]" type="text" value="" /></span></p>

A single line that simplifies your life ;)