How to highlight fields on Rails validation errors

How do you display highlighting field fields for fields that do not allow validation errors in Rails 3.1? I know scaffolding automatically generates css and controller code to handle this, but I was wondering if there is a way to create this manually. I have already implemented the string display of error messages via: @ user.errors.full_messages.each ... etc., but I can not make the fields highlight in red. Any ideas?

Thanks.

+8
ruby validation ruby-on-rails validationerror
source share
3 answers

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?

Optional : here is a section on setting the default authentication of ActiveRecord CSS.

Edit: (about additional 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) %> [...] 

(Maybe I'm wrong - I write by phone, but you get a general idea. You can encode it in several ways = infinity, so do as you like ...)

+21
source share

Rails now has a good trick. When an error rails occurs, it places a div with the .field_with_errors class around the error fields. So now you can just target this 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 beautiful red line around the input element although this is important! will overwrite any existing styles.

+4
source share

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

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

0
source share

All Articles