Fully custom validation error message with Rails
Using Rails I'm trying to get an error message like "The song field can't be empty" on save. Doing the following:
validates_presence_of :song_rep_xyz, :message => "can't be empty"
... only displays "Song Rep XYW can't be empty", which is not good because the title of the field is not user friendly. How can I change the title of the field itself ? I could change the actual name of the field in the database, but I have multiple "song" fields and I do need to have specific field names.
I don't want to hack around rails' validation process and I feel there should be a way of fixing that.
Now, the accepted way to set the humanized names and custom error messages is to use locales.
# config/locales/en.yml
en:
activerecord:
attributes:
user:
email: "E-mail address"
errors:
models:
user:
attributes:
email:
blank: "is required"
Now the humanized name and the presence validation message for the "email" attribute have been changed.
Validation messages can be set for a specific model+attribute, model, attribute, or globally.
Try this.
class User < ActiveRecord::Base
validate do |user|
user.errors.add_to_base("Country can't be blank") if user.country_iso.blank?
end
end
I found this here.
Here is another way to do it. What you do is define a human_attribute_name method on the model class. The method is passed the column name as a string and returns the string to use in validation messages.
class User < ActiveRecord::Base
HUMANIZED_ATTRIBUTES = {
:email => "E-mail address"
}
def self.human_attribute_name(attr)
HUMANIZED_ATTRIBUTES[attr.to_sym] || super
end
end
The above code is from here
In your model:
validates_presence_of :address1, :message => "Put some address please"
In your view
<% m.errors.each do |attr,msg| %>
<%=msg%>
<% end %>
If you do instead
<%=attr %> <%=msg %>
you get this error message with the attribute name
address1 Put some address please
if you want to get the error message for one single attribute
<%= @model.errors[:address1] %>
链接地址: http://www.djcxy.com/p/63550.html
下一篇: 使用Rails完全自定义验证错误消息