9

How do you display form field highlighting for fields that fail validation errors in Rails 3.1? I know that scaffolding automatically generates the css and controller code to handle this, but I was wondering if there was a way to generate that manually. I have already implemented the string display of error messages through: @user.errors.full_messages.each...etc, but I can't get the fields to become highlighted in red. Any ideas?

Thanks.

kdhuang
  • 129
  • 1
  • 1
  • 6

3 Answers3

23

Assuming you have an error class for fields in your CSS file:

<% if @user.errors[:name] %>
  <%= f.label :name, :class => "error" %>
<% else %>
  <%= f.label :name %>
<% end %>

Is this what you want?

Extra: here's a section about customizing default ActiveRecord validations CSS.

Edit: (about extra ifs)

# app/helpers/application_helper.rb

def field_class(resource, field_name)
  if resource.errors[field_name]
    return "error".html_safe
  else
    return "".html_safe
  end
end

And then:

# in your view

<%= f.label :name, :class => field_class(@user, :name) %>
<%= f.label :password, :class => field_class(@user, :password) %>
[...]

(I may have make a mistake in there - I'm writing on a phone - but you get the general idea. You can code this in number of ways = infinity, so do it the way you like...)

Wazery
  • 15,394
  • 19
  • 63
  • 95
Jakub Naliwajek
  • 707
  • 5
  • 9
  • Thanks. That works, but that would mean I would have to do an if for each form field... – kdhuang Aug 31 '12 at 21:32
  • See edit. I bet you could code it even inline if you like. Or you could even override `label` itself and don't have to ever write any extra characters. – Jakub Naliwajek Aug 31 '12 at 21:45
  • 2
    I love this bit of code and have been using it for a while now. This is fewer lines for those happy saving space... `resource.errors[field_name].present? ? "error".html_safe : "".html_safe` – notrab Dec 03 '13 at 10:05
  • There is method for this now `@user.errors.include?(:name)` http://api.rubyonrails.org/classes/ActiveModel/Errors.html#method-i-include-3F – Artem P Jul 14 '17 at 17:08
10

Rails now have a nice trick up its sleeve..When an error occurs rails put a div with a class .field_with_errors around the error fields. So now you can just target that class and add styling.

To focus on the input you can do

.field_with_errors input{
  border: 1px solid red !important;
}

this css will put a nice red line around the input element while important! will overwrite any existing styles.

Abhilash
  • 2,864
  • 3
  • 33
  • 67
0

I had to do this (resource.errors[field_name].length > 0) to get it to work:

def field_class(resource, field_name) if resource.errors[field_name].length > 0 return " custom_error1 ".html_safe else return "".html_safe end end

Greg Lafrance
  • 768
  • 1
  • 7
  • 18