Skip to content

Instantly share code, notes, and snippets.

@gitjul
Created September 20, 2017 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gitjul/8802cf6f9281315a72e1457720c5a916 to your computer and use it in GitHub Desktop.
Save gitjul/8802cf6f9281315a72e1457720c5a916 to your computer and use it in GitHub Desktop.
Add an error class to invalid fields and labels, overriding the standard Rails behaviour of wrapping them in div.field_with_errors
# /config/initializers/field_with_error.rb
# Based on https://gist.github.com/niklas/772018
ActionView::Base.field_error_proc = proc do |html_tag, _instance|
if html_tag.match? %r{<(input|label|textarea|select)}
error_class = "has-error"
doc = Nokogiri::XML(html_tag)
doc.children.each do |field|
next if field["type"] == "hidden"
next if field["class"].match? %r{\b#{error_class}\b}
field["class"] = "#{field['class']} #{error_class}".strip
end
doc.to_html.html_safe
else
html_tag
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment