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

COMMENTS / ONE COMMENT

I’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?

clay added these pithy words on Aug 12 08 at 2:54 pm

SPEAK / ADD YOUR COMMENT
Comments are moderated.

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

Return to Top

Custom field_error_proc in Ruby on Rails

FRESH / LATEST POSTS

Thankful for...Thankful for...Thankful for...Thankful for...Thankful for...Thankful for...Thankful for...Thankful for...

Online

AIM : Online

Powered by IM Online