可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
回答1:
Assuming you have an error class for fields in your CSS file:
"error" %>
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 field_class(@user, :name) %> 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...)
回答2:
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 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.
回答3:
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