Created
January 9, 2011 21:03
-
-
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
This file contains 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
# 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 |
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
This is great, thanks!