How to Highlight Fields on Rails Validation Errors

落花浮王杯 提交于 2019-11-30 09:20:45
Jakub Naliwajek

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

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!