Tip #14 - Custom Error Messages in Validations
2008-04-22 18:10:20 +0000
If you use Rails, you sometimes get a situation where the custom error messages just don’t work, here is how you can fix it…
Say you have a model with a field called ‘country_iso’ which specifies the ISO value of the country the person belongs to.
Database design concerns aside (you should really have it as country_id and a separate country_iso field) you might be stuck with this situation from a legacy database (like I was).
As this is a required field, you set the following in your model:
1 2 3 |
class User < ActiveRecord::Base validates_presence_of :country_iso end |
So, you go ahead and make a form which presents the country as just a select box, because you don’t want your users to worry about if Thailand is TH or TL, but then you don’t specify a country and the error message comes back to the user in nice big letters:
Country Iso can’t be blank
Ugh!
Aside from the fact that Iso is capitalized badly, how many of YOUR users know that it stands for “International Standards Organization” and that a Country ISO is usually a two letter representation of the country? I’d wager about 3 of them have some idea :)
So you go in and change the validates line to:
1 2 3 |
class User < ActiveRecord::Base validates_presence_of :country_iso, :message => "Country can't be blank" end |
Do your test again, and now you get:
Country Iso Country can’t be blank
Nup.. that’d didn’t really fix it.
Fortunately, the fix is easy:
1 2 3 4 5 |
class User < ActiveRecord::Base validate do |user| user.errors.add_to_base("Country can't be blank") if user.country_iso.blank? end end |
Now, reload your view and you’ll get:
Country can’t be blank
Much better!
blogLater
Mikel
Leave a Reply
Latest posts
- Rails Security Alert
- Encrypting Another Partition Using FileVault 2 on OSX Lion
- Installing Home Folder on Second Drive on OSX Lion
- undefined local variable or method `version_requirements'
- A New World of Resources
- Rails Static Pages
- Twitter Replacing Rails? So?
- Engine Yard Cloud Backups Generating Zero Length Backups
- Our Rails Rumble Entry - StillAlive.com
- Renaming a controller and redirection in Rails 3
- Updating RailsPlugins.org to Rails 3 - Part 1
- A new protocol for social interaction
- What is a distributed social network?
- Bundler and Public Git Sources
- Getting Heroku, memcached and Rails 3 working
- Why Bundler?
- Rails Commit Access
- Introducing TellThemWhen
- rake RSpec & Cucumber uninitialized constant Rails::Boot::Bundler
- This Relationship is Worth Nothing
- Thank YOU...
- Inline Attachments for ActionMailer
- Upgrading RailsPlugins.org to Rails 3 - Part 1
- Stripping dollar signs and commas from a string
- Getting Rails 3 Edge with jQuery, RSpec and Cucumber using RVM
- Action Mailer, go Proc thyself
- The Real News Donation Drive
- ActionMailer ScreenCast and Article
- Installing RSpec for Rails 3
- I am speaking at RailsConf 2010
- Rails 3 Session Secret and Session Store
- If you're lazy and you know it write your specs!
- Bundler - uninitialized constant ActionController
- Bundle Me Some Sanity
- How to use Mail / ActionMailer 3 with GMail SMTP
- Put your mailer where the action is!
- Why Force a Choice?
- How to make an RSS feed in Rails
- Rails 3 Routing with Rack
- Bundle me some Rails
- Helping out in Haiti
- Watch your self
- Is Rails 3.0 a Game Changer?
- Where did the scripts go?
- validates :rails_3, :awesome => true
- New Rails Version 3.0 Guides Online
- New ActionMailer API in Rails 3.0
- Mail gem version 2 released
- How to rename a Rails 3 Application
- Rails 3.0 Examples
Latest comments
- Victor1122
Your blog provided us with valu...
- Accelerate High Growth Business Training
Nice!!! It’s really very inform...
- Accelerate High Growth Business Training
Nice!!! It’s really very inform...
- Accelerate High Growth Business Training
Nice!!! It’s really very inform...
- kGygKevM
[url=http://www.79KF7rE5EliB48J...
Categories
Tag Cloud
AJAX ARGH! ActiveRecord Ajax Apache Apple Asterisk Australia Copy Database Development Feedburner Gem server Google Human Rights Javascript L. Ron Hubbard MS SQL Server MacOSX Mail Mephisto Not Programming OpenBSD Opensource Performance Personal Integrity PostgreSQL Programming Prototype Puzzle RDoc REST RESTful Rails RSPec RSpec Rails Rails Tips Rspec Ruby Ruby on Rails Ruby on Rails Tips Ruby on rails Tips SQL SQLServer SVN Scientologist Scientology Site Stats Soekris Soekris net5501 TMail Textmate Tips Windows World about mikel anti drug apache contributing daemon documentation drugs illustrator javascript lambda mail mephisto newspapers nitro open source opensource photoshop productivity programming railscasts rspec ruby ruby on rails rubyforge scientology seo sitemap sqlserver tips tmail tom cruise unix tricks vector graphicsArchives
- November 2009 (1)
- October 2009 (2)
- September 2009 (2)
- August 2009 (0)
- July 2009 (1)
- June 2009 (0)
- May 2009 (1)
- April 2009 (0)
- March 2009 (0)
- February 2009 (0)
- January 2009 (2)
- December 2008 (0)
- November 2008 (5)
- October 2008 (0)
- September 2008 (1)
- August 2008 (0)
- July 2008 (2)
- June 2008 (13)
- May 2008 (7)
- April 2008 (18)
- March 2008 (8)
- February 2008 (5)
- January 2008 (7)
- December 2007 (20)
- November 2007 (22)




2008-05-07 03:57:55 +0000
Hey Great Tip! Thanks for the post. Any idea how to make sure that the form field remains tagged properly with the appropriate error class so that the css rule for an error field will be applied properly? ~Ben
2008-05-11 19:49:58 +0000
Ben: You could also do http://henrik.nyh.se/2007/12/change-displayed-column-name-in-rails-validation-messages
2008-05-18 01:12:08 +0000
In fact I should have put this code to ApplicationController along with ActiveRecord::Errors.default_error_messages = { …
2008-11-26 11:32:12 +0000
How to use it in error_messages_for ???
2011-02-18 16:16:50 +0000
I have found another way of doing this, I think it is simpler:
validates_presence_of :country_iso, :message => “Sorry! Country can’t be blank”Just keep the model with the validations statement, as you would normally
And then, in the view, change
<% @client.errors.full_messages.each do |msg| %>to
<% @user.errors.each do |attr,msg| >
< end %>
And that’s it.
This way you dont mess your css tags.
@client.erros acctually returns a hash where the attribute is the key, and the msg is the value.
by the way, great blog, have helped me alot.
2008-05-11 17:46:07 +0000
Ben: You could do http://henrik.nyh.se/2007/12/full-error-messages-without-prepended-attribute-name.
I believe another way would be to add_to_base and then add a nil error to the attribute: user.errors.add(:country_iso, nil)
nil errors should not be listed in text but still get you the CSS error highlighting.
2008-05-11 20:19:58 +0000
Henrik: Nice solution! Go read Henrik’s solution, it’s quite neat!
2008-05-11 22:45:46 +0000
Is there a way to change the table name as well for the error message? For example, I have an STI model “class Group < Assembly” so when there is an error saving a Group, the error message says “2 errors prohibited this assembly from being saved” but I would like it to say “3 errors prohibited this group from being saved”.
2008-05-14 04:02:43 +0000
The way I do this is by specifying full error messages for all my attributes, and then using a custom FormBuilder that displays the messages with the field (i.e., I do not use error_messages_for). With this approach, you get the benefit of having the error messages associated with the invalid attribute.
I think the default messages are kind of like scaffolding: good for getting started, but I wouldn’t use them in a real app.
2008-05-18 00:31:29 +0000
I would suggest better way:
class User < ActiveRecord::Base
ActiveRecord::Errors.class_eval do alias user_add add def add(attribute, msg) user_add( User.field_names[attribute.to_sym] || attribute, msg ) end end@@field_names = {
:country_iso => ‘Country’
}
cattr_reader :field_names
…
Why? Because you can use all validates_… methods and regular error processing (how are you going to use validates_uniqueness_of?). Drawback – translation is application-wide, so User.country_iso and Session.country_iso will be translated exactly same way. Bad for existing applications where you can not choose fields.
2008-05-19 15:14:42 +0000
Great! I’d like to ask if there is a way to change default texts in header and bellow header:
“5 errors prohibited this order from being saved
There were problems with the following fields:”
Reason – localization into different language
Thanx
2008-05-20 21:16:08 +0000
yea Peter go check out this page:
http://www.softiesonrails.com/2008/4/23/better-messages-for-activerecord-validation-errors
2008-05-21 09:56:15 +0000
As for me I am using
begin
@User.save!
rescue Exception => e
flash.now[ :user_errors ] = e.message
render :action => :new
end
Might not be the best thing of course, but resulting error message is concise and helps in case of other errors, not just database.
2008-05-21 10:09:28 +0000
Still don’t know how to paste code. You can check here -
http://pastie.textmate.org/201339
Meanwhile working example of my previous post can be found here (full translation of error messages & field names) –
http://pastie.textmate.org/201340
I happened to be a bit more complex than I expected.
2013-04-04 19:14:57 +0000 Деньги до миллиона, низкий % 8(495)769-53-05 Игорь (Москва)
2013-04-15 23:41:00 +0000
Children’s tooth development begins while the baby is in the womb. Teething usually occurs between the ages of six and nine months. Children usually have their full set of 20 primary teeth (milk teeth, baby teeth or deciduous teeth) by the age of three years. At about the age of six years, the first permanent teeth erupt (push through the gum).
2013-04-24 21:46:53 +0000
F*ckin’ amazing things here. I’m very glad to see your article. Thanks a lot and i am looking forward to contact you. Will you kindly drop me a e-mail? site
2013-04-26 19:43:02 +0000
This web page is really a stroll-via for the entire info you needed about this and didn’t know who to ask. Glimpse here, and also you’ll positively uncover it. CENTRUM EUROPY – szwedzki warszawa
2013-05-02 18:31:53 +0000
Very nice post. I just stumbled upon your blog and wanted to say that I have really enjoyed browsing your blog posts. In any case I’ll be subscribing to your rss feed and I hope you write again soon! zespół na wesele bydgoszcz
2013-05-10 06:08:13 +0000
It’s laborious to seek out knowledgeable folks on this matter, however you sound like you know what you’re talking about! Thanks ALDO TECHNIKA GRZEWCZA SŁAWOMIR WIŚNIEWSKI
2013-05-10 06:07:35 +0000
Good day! This post couldn’t be written any better! Reading this post reminds me of my previous room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thank you for sharing! PHU ALDO TECHNIKA GRZEWCZA SŁAWOMIR WIŚNIEWSKI
2013-05-10 06:08:47 +0000
Heya i am for the first time here. I came across this board and I find It really useful & it helped me out much. I hope to give something back and help others like you helped me. ATGSW
2013-05-10 06:08:26 +0000
I do agree with all the ideas you’ve presented in your post. They’re really convincing and will definitely work. Still, the posts are very short for novices. Could you please extend them a little from next time? Thanks for the post. ALDO – pompy ciepła
2013-05-20 15:19:40 +0000
]
kGygKevM http://www.79KF7rE5EliB48Jl5Ar42Q.com/
kGygKevM
2013-05-20 15:10:55 +0000
Howdy just wanted to give you a brief heads up and let you know a few of the pictures aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different browsers and both show the same outcome. website
2013-05-20 15:10:15 +0000
Hi, I think your blog might be having browser compatibility issues. When I look at your website in Safari, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, terrific blog! hpv Białystok
2013-05-20 15:10:52 +0000
whoah this weblog is excellent i really like studying your posts. Stay up the great paintings! You understand, a lot of persons are searching round for this info, you could aid them greatly. Prowadzenie ciąży Białystok