Created
September 20, 2017 14:40
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# /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