[Rails] Changing default behavior of fieldWithErrors

Paul Ingles paul at engross.org
Fri Feb 24 12:45:03 GMT 2006


I'd like to say I came up with this, but I actually found it somewhere else.

I have the following inside my environment.rb file:

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
  msg = instance.error_message
  error_style = "background-color: #f2afaf"
  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

Although at the moment this just sets the style to a background colour,
you could change it to set the class the be whatever you wanted.

Regards,
Paul

> Hi!
>
> The topic can be a bit misleading, because it may suggest that i want to
> change css style.
>
> What i'd like to change is that normally, when there's an error, rails
> creates a div element with the fieldWithErrors class as the parent of
> the input. I'd like to change this behavior, so the input element itself
> will have this class added to its current classes and removed if
> there're no more errors.
>
> How it can be (easily) done?
>
> --
> Posted via http://www.ruby-forum.com/.
> _______________________________________________
> Rails mailing list
> Rails at lists.rubyonrails.org
> http://lists.rubyonrails.org/mailman/listinfo/rails
>



More information about the Rails mailing list