Fully custom validation error message with Rails
Solution 1:
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.
Solution 2:
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] %>
Solution 3:
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.
Update for Rails 3 to 6:
validate do |user|
user.errors.add(:base, "Country can't be blank") if user.country_iso.blank?
end
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
Solution 4:
Yes, there's a way to do this without the plugin! But it is not as clean and elegant as using the mentioned plugin. Here it is.
Assuming it's Rails 3 (I don't know if it's different in previous versions),
keep this in your model:
validates_presence_of :song_rep_xyz, :message => "can't be empty"
and in the view, instead of leaving
@instance.errors.full_messages
as it would be when we use the scaffold generator, put:
@instance.errors.first[1]
And you will get just the message you specified in the model, without the attribute name.
Explanation:
#returns an hash of messages, one element foreach field error, in this particular case would be just one element in the hash:
@instance.errors # => {:song_rep_xyz=>"can't be empty"}
#this returns the first element of the hash as an array like [:key,"value"]
@instance.errors.first # => [:song_rep_xyz, "can't be empty"]
#by doing the following, you are telling ruby to take just the second element of that array, which is the message.
@instance.errors.first[1]
So far we are just displaying only one message, always for the first error. If you wanna display all errors you can loop in the hash and show the values.
Hope that helped.