I was recently working a project that required pixel perfect CSS so Ruby on Rail’s packaged field_error_proc just wouldn’t cut it. If you’ve ever written a scaffold with validations you’re familiar with what I’m talking about. The injection of the field_with_errors div wrapped around the offending field. I needed to highlight the field’s background with a different color to let the user know there was an error. Here’s what I did to work around the default.
Create a new file: initializers/custom_error_proc.rb
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
#%(<span>*</span>) + html_tag
error_style = "background-color: #ffff80"
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}' "
end
html_tag
end
- BROWSE / IN TIMELINE
- « Mediocrity in the Workplace
- » Custom Validation for attachment_fu
- BROWSE / IN Code Ruby on Rails
- « Refactor Your WetWare
- » Custom Validation for attachment_fu
COMMENTS / ONE COMMENT
clay added these pithy words on Aug 12 08 at 2:54 pmI’ve used this snippet, but havent solved one problem…
If the error needs to be shown for a checkbox followed by a label (e.g. accepting TOS), the erro gets inserted between the checkbox and its label text.
Have you figured out a solution for that?
SPEAK / ADD YOUR COMMENT
Comments are moderated.










