Custom Validation Messages
8 errors prohibited this account from being saved
There were problems with the following fields:
…
Maybe it is just me, but having error messages like the above seems a little to artificial to me. Maybe rails has standard error messages like the following so everybody changes them, who knows.
One thing I found when searching for customized error formatters is that they would only accept one model object reference, ie, they would only allow for
error_messages_for(:account)
and not
error_messages_for(:account, :user)
which is odd seeing as the overridden method does allow for many models.
Below is a custom method that will allow us to deliver the message with more of a person to person flavour.
def error_messages_for(*object_names) messages = [] object_names.each do |object_name| object = instance_variable_get("@#{object_name}") if object && !object.errors.empty? object.errors.full_messages.each do |message| messages << %(<li>#{message}</li>) unless message =~ /is invalid/ end end end if messages.size > 0 content_tag(:div, content_tag(:h2, "Uh-oh! We have some invalid fields.") + content_tag(:ul, messages),:id => 'errors') end end
It will also prevent messages like “Users is invalid” (yes that is pluralized on purpose) that occur from having the validates_associated :user validator telling us that the associated model is invalid.
This isn’t groundbreaking, but I know I will be searching for this again sometime soon.
Trackbacks
Trackbacks are closed.
