Aug 19

fieldWithErrors Overrides my CSS Field Classes

etienne @ 6:07 pm

When there are errors on a form, Rails will normally create a <DIV> element with the fieldWithErrors class wrapped around the fields input statement. If you have your own CSS class wrapped around a field this will be overridden by the fieldWithErrors <DIV> which is a pain.

I was searching for a solution when I found this post:

I’d like to say I came up with this, but I actually found it somewhere else.

I have the following inside my environment.rb file:

ActionView::Base.field_error_proc = do |html_tag, instance|
  msg = instance.error_message
  error_style = "background-color: #f2afaf"
  if html_tag =~ /<(input|textarea|select)[^>]+style=/
    style_attribute = html_tag =~ /style=[’"]/
    html_tag.insert(style_attribute + 7, "#{error_style}; ")
  elsif html_tag =~ /<(input|textarea|select)/
    first_whitespace = html_tag =~ /\s/
    html_tag[first_whitespace] = " style=’#{error_style}’ "

I now get the desired effect when an error occurs, in my case it changes the background color of the field red, you can change it to whatever effect you want without it interfering with your field CSS classes…perfect!

2 Responses to “fieldWithErrors Overrides my CSS Field Classes”

  1. poster says:

    this one doesn’t work … i guess it’s the ‘”

  2. etienne says:

    If you directly copy/paste the code from this page to your editor you may need to delete/replace the single quotes in ’#{error_style}’ for example. At some stage I will install the code syntax plugin that will allow direct copy/paste of code.

Leave a Reply