Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save niklas/772018 to your computer and use it in GitHub Desktop.
Save niklas/772018 to your computer and use it in GitHub Desktop.
Add .error CSS class to all invalid form fields. Rails wraps them in div.fieldWithErrors, which still sucks in 3.0
# put this in config/initializer/fields_with_errors.rb
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
if html_tag =~ /<(input|label|textarea|select)/
error_class = 'error'
doc = Nokogiri::XML(html_tag)
doc.children.each do |field|
unless field['type'] == 'hidden'
unless field['class'] =~ /\berror\b/
field['class'] = "#{field['class']} error".strip
end
end
end
doc.to_html.html_safe
else
html_tag
end
end
@rreynier
Copy link

This is great, thanks!

@brendon
Copy link

brendon commented Jun 11, 2014

Hey, I had the old hpricot based patch on which this is based. You've skipped one bit which might be important. It checks to see if the child is an element or not (as in not a text node).

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
  if html_tag =~ /<(input|label|textarea|select)/
    doc = Nokogiri::XML(html_tag)
    doc.children.each do |field|
      unless !field.elem? || field['type'] == 'hidden' || field['class'] =~ /\berror\b/
        field['class'] = "#{field['class']} error".strip
      end
    end

    doc.to_html.html_safe
  else
    html_tag
  end
end

The error_class variable isn't required in your version so I've taken that out :)

Thanks for making this a quick and easy upgrade!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment