Customize error message with simple_form
You can declare the content of the error message in your model:
validates_length_of :name, :minimum => 5, :message => "blah blah blah"
You can set
id
orclass
for your error tag:<%= f.input :name, :error_html => { :id => "name_error"} %>
Then you can use CSS for the styling.
And you can use
<%= f.error :name, :id => "name_error" %>
and you'll get
<span class="error" id="name_error">is too short (minimum is 5 characters)</span>
I dont know if it is any different for simple_form gem.
For content of error messages to be changed, you can use the :message
attribute in the model.
class User < ActiveRecord::Base
validates :email, {:presence => true, :message => "is not filled up."}
end
Now the validation message will be Email is not filled up
. If you want the field name also to be changed(Email
to E-mail address
something like that ), the approach now is to define it in locales.rb
file like this
# config/locales/en.yml
en:
activerecord:
attributes:
user:
email: "E-mail address"
See link for details on locales
. Another approach is to define in the model, humanized attributes like this:
class User < ActiveRecord::Base
validates :email, {:presence => true, :message => "is not filled up."}
HUMANIZED_ATTRIBUTES = {
:email => "E-mail address",
...(other fields and their humanized names)
...
}
def self.human_attribute_name(attr, options={})
HUMANIZED_ATTRIBUTES[attr.to_sym] || super
end
end
For customizing style of validation message we will have to edit the style for
#errorExplanation
and .fieldWithErrors
,in the scaffold.css
stylesheet.
You can easily change the default error message comes in the translation file, which is found in config/locales/simple_form.en.yml
.
In the specific initializer, config/initializers/simple_form.rb
you can overrule the default options how the html is generated.
Hope this helps.
For completeness, I would like to add that formtastic is an easier choice to start with, because it has a default layout. I like simple_form a lot, but it does not offer any formatting out of the box, but that is their intention. With Formtastic it is very hard (impossible) to change the generated html, and with simple_form can you can completely mold the generated html to your liking. This is especially useful if you have a designer, and the forms you generate have to generate the same html. So if you are getting started, formtastic will give you nicer-looking results quicker. Also note that it is quite easy to switch, because the syntax is almost identical.