Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Highlight Fields on Rails Validation Errors

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.

like image 842
kdhuang Avatar asked Aug 31 '12 21:08

kdhuang


People also ask

Can we save an object in DB if its validations do not pass?

If any validations fail, the object will be marked as invalid and Active Record will not perform the INSERT or UPDATE operation. This helps to avoid storing an invalid object in the database. You can choose to have specific validations run when an object is created, saved, or updated.


1 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?

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...)

like image 171
Jakub Naliwajek Avatar answered Sep 27 '22 00:09

Jakub Naliwajek