#211
Apr 26, 2010

Validations in Rails 3

Rails 3 offers several new additions to validations. Here learn how to make a custom error_messages partial, reflect on validations, and clean up complex validations in a model.
Download (14.4 MB, 9:53)
alternative download for iPod & Apple TV (14.3 MB, 9:53)

Resources

gem install rails --pre
gem cleanup
rails store
cd store
rails g scaffold user name:string email:string
rake db:migrate
<!-- users/_form.html.erb -->
<%= form_for(@user) do |f| %>
  <%= render "shared/error_messages", :target => @user %>
  
  <div class="field">
    <%= f.label :name %><%= mark_required(@user, :name) %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :email %><%= mark_required(@user, :email) %><br />
    <%= f.text_field :email %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

<!-- shared/_error_messages.html.erb -->
<% if target.errors.any? %>
<div id="errorExplanation">
  <h2><%= pluralize(target.errors.count, "error") %> prohibited this record from being saved:</h2>
  <ul>
  <% target.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
  <% end %>
  </ul>
</div>
<% end %>
# application_helper.rb
def mark_required(object, attribute)
  "*" if object.class.validators_on(attribute).map(&:class).include? ActiveModel::Validations::PresenceValidator
end

# models/user.rb
validates :email, :presence => true, :uniqueness => true, :email_format => true

# lib/email_format_validator.rb
class EmailFormatValidator < ActiveModel::EachValidator
  def validate_each(object, attribute, value)
    unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
      object.errors[attribute] << (options[:message] || "is not formatted properly") 
    end
  end
end

RSS Feed for Episode Comments 39 comments

1. Rya Apr 26, 2010 at 07:30

Awesome, always looking forward to the Mondays railscast, even if it was late today :)


2. Ben Apr 26, 2010 at 07:42

Thanks, Awesome as allways :)


3. Alan Maciel Apr 26, 2010 at 08:14

All new projects in ubernetics will be developed in Rails 3, all this rails 3 series railscasts help me to take this decision.. thanks Ryan!! Rails 3 here we go!!!!


4. Jon Apr 26, 2010 at 08:57

Really appreciate the good work Ryan. Thanks!!


5. ryeguy Apr 26, 2010 at 09:01

This video was really glitchy for me -- but all of the past videos have been fine. There were many parts where the frame wouldn't completely be painted when transitioning to a new screen. For example, when switching from the console to the browser, I would still see the console, but could see the cursor kind of "painting" the web browser in. Hard to explain. I think it's encoded poorly. Have you tried using xvid?


6. ryeguy Apr 26, 2010 at 09:09

To ammend the above, this problem was only when using VLC player. But as I said before, I have never had this problem with any of your other videos.


7. Ryan Bates Apr 26, 2010 at 09:20

@ryeguy, I'm experimenting with various video codec settings. Were you watching the full resolution or the iPod/AppleTV one?


8. dpf Apr 26, 2010 at 09:21

same here on the glitchy video. Content is great - but for the first time - the video doesn't update when you've switched views (from textmate to safari for example) for 5 - 10 seconds and is pixelated too.

Thanks Ryan.


9. Ryan Bates Apr 26, 2010 at 09:22

@dpf, are you using VLC player?


10. Alan Apr 26, 2010 at 09:23

What would we do without you?

Over the last few episodes I have been convinced that I should be heading in the RoR 3 direction sooner rather than later.

A big 'thank you' Ryan.


11. dpf Apr 26, 2010 at 09:25

@ryeguy is right - same experience here - the video is fine in totem - but messed up in VLC. Perhaps this isn't worth addressing given the small population of us it effects.


12. Jamie Hill Apr 26, 2010 at 10:02

Thanks for the summary Ryan. I was the author of "Sexy Validations", you can see my original writeup here: http://thelucid.com/2010/01/08/sexy-validation-in-edge-rails-rails-3/


13. ryeguy Apr 26, 2010 at 11:08

Ryan - the problem was with the full version of the video. Didn't try the iphone/pod version.


14. Stefan Huska Apr 26, 2010 at 11:33

Here is my simple RoR plugin for custom error template:

http://github.com/kelso/render_errors


15. Wlodek Bzyl Apr 26, 2010 at 12:42

If mail is not formatted properly, then the asterisks '*' is rendered between two div's.

Is there a simple way to move '*' into the first div?

<div class="fieldWithErrors"><label for="user_email">Email</label></div>*<br />
    <div class="fieldWithErrors"><input id="user_email" name="user[email]" size="30" type="text" value="x" /></div>


16. KAMiKZ Apr 26, 2010 at 16:00

Great Ep as always Ryan Thanks!

I am on Win7 64bit, VLC does have a problem rendering. Media Player Classic has no problem. And since WMP uses the same codec as does MPC, it plays it fine, as well. Just VLC then.

Regards


17. At Ryan Bates Apr 26, 2010 at 16:11

Hey rbates, thank you for your useful and awesome casts! Ryan, PLEASE, can you "Build an entire application over a series of screencasts" with Rails 3, where you can cover all other sub-topics like this validation and other devise and etc. Please, do not neglect this comment and make me and people who want to see you build entire apps happy. I would even pay to watch those. Thanks!


18. Sterling Apr 26, 2010 at 21:15

FYI Ryan: I too have the same issue with the full version using VLC


19. mario Apr 26, 2010 at 22:58

Video works fine for me on VLC 10.6, Snow Leopard 10.6.3 (as well as in QuickTime)


20. mario Apr 26, 2010 at 22:58

er, i meant VLC 10.5


21. Marius Apr 27, 2010 at 04:14

Works under OSX 10.5 with movist.
Works under linux with kaffeine qt4, it doesn't work with smplayer or mplayer.


22. Bijan Apr 27, 2010 at 06:59

Hey Ryan,

thanks a lot for this episode.
Some time ago I searched for a clever solution and ended up with formtastic in combination with validation reflection. Would you prefer formtastic over this more barebone approach with less abstraction?
For me it is important to get going fast and to have maintainable code I can adjust if I need to.

Kind regards
Bijan


23. Gang Apr 27, 2010 at 07:10

It's very nice and clean.
Thanks.


24. Paolo Apr 27, 2010 at 23:40

Thanks again for the new episode.
Ruby-3 seems really wonderful


25. vladimir prieto Apr 28, 2010 at 06:04

this is the first time video file doesn't play nice. i mean, there were freezed frames all over the cast.

don't know if it is my linux machine (ubuntu 9.10) or the player (vlc).

so, i want to know if you (Ryan) made it in a different way (different kind of codec may be). that way, i could see other alternatives.

thanks.


26. At Pauolo Apr 28, 2010 at 08:50

@Pauolo

You mean Rails 3?


27. tobago May 03, 2010 at 09:25

Aaaaawesome!
Having classes of validations is really a step forward.


28. harris May 05, 2010 at 01:30

i want to know if you (Ryan) made it in a different way (different kind of codec may be). that way, i could see other alternatives.
thanks.<a href="http://www.cissplearn.com">cissp training</a>


29. SingleSally May 25, 2010 at 07:11

Great stuff, I shall add it to my favourites.


30. Michaël Rigart May 26, 2010 at 12:51

Nice cast. But one thing that struck me. How do you translate the those validation messages when you use the self made partial as shown in this cast?


31. frank Jun 22, 2010 at 00:23

David Heinemeier Hansson


32. Christian Louboutin sale Jun 25, 2010 at 00:42

Thanks for informing.


33. Кинотеатры Барнаула Jul 01, 2010 at 22:34

Awesome, always looking forward to the Mondays railscast

PS Барнаульский дендрарий, Барнаул ДубльГис, Где отдохнуть в Барнауле, Кинотеатры Барнаула, Легенды Барнаула


34. Jerseys Jul 18, 2010 at 22:20

Good post, thanks for sharing, I enjoy it very much!


35. Air Jordan Sale Jul 23, 2010 at 17:01

thank you for sharing...that's is very great


38. helmerj Jul 27, 2010 at 00:54

The custom validator used here to validate an email address does not work in the just released rc of rails3:

Unknown validator: 'email_format'

So stuff in RAILS_ROOT/lib does nto get loaded I suppose...

Anybody know how to solve this?


38. helmerj Jul 27, 2010 at 00:59

Well should have done my research properly...

The custom validators have to go here:

app/validators

Cheers J


40. Ivan Aug 06, 2010 at 08:05

Good post.

But
<%= render :partial => 'shared/error_messages', :target => @user %> does not work for me.
I have "undefined local variable or method `target'" error

So I use
<%= render :partial => 'shared/error_messages', :locals => {:target => @user} %>


40. fadewatches Aug 07, 2010 at 00:06

I am a fanatic watch collection, especially the well-known watches, you also can do, just click on my name!!!!!!!!


41. UGG Boots on sale Aug 10, 2010 at 18:42

Gooooooooooooooooooood luck ~~!!


42. UGG Classic Argyle Knit Aug 12, 2010 at 00:12

  The perfect!These articles written too great,they rich contents and data accurately.they are help to me.I expect to see your new share


43. store directory Aug 13, 2010 at 22:38

It is unusual though. Does anyone here know Ryan personally?


44. oppo Aug 15, 2010 at 08:38

This was really useful. Thanks Ryan!


45. replica jerseys Aug 17, 2010 at 08:32

nice article, thanks for sharing this with us here!!!


46. Rip Blu-ray for Mac Aug 18, 2010 at 01:35

Thanks,it's so good.
suport!


47. AVI to iPad Aug 19, 2010 at 00:53

This was really useful.


48. air jordan retro 1 Aug 19, 2010 at 23:00

very nice post

i like it

thanks for sharing

look forward new posts


49. wholesale new era caps Aug 20, 2010 at 20:05

Fantastic Read! Looking forward to more! Bookmarked the site and will be back again!


50. converse all star Aug 20, 2010 at 20:51

love converse all star,love yourself.High quality low price.It's fit for you.


51. jordan shoes on sale Aug 20, 2010 at 22:56

have become a huge fan of this website and I really cant wait to read you next posts! I really enjoy watching the RailsCasts. I think type of site that is useful in sharing information and it is important to share. very thanks for this screencast.


52. 传奇私服 Aug 21, 2010 at 00:02

I have been reading your posts during my afternoon break, and I must admit the whole article has been very useful and very well written. I thought I would let you know that for some reason this blog does not display well in Internet Explorer 8. I wish Microsoft would stop changing their software. I have a question for you. Do you mind exchanging blog roll links? That would be really cool!


53. Jordan 1 Aug 23, 2010 at 02:17

Nice blog, now, discount jordan shoesI found a new atmosphere here and you have a nice info to share, Air Jordan2 I really like this, and hope you’re always happy to share this every single day,thanks alot for your information, Air Jordan 1 I’ll bookmark this and share to all my friend for dropping at here, have a nice day… air jordan2 shoes,air force 1s


54. Jordan 2 Aug 23, 2010 at 02:17

The article is very well!


55. hzcy Aug 23, 2010 at 23:26

Any member of your group can post to your trip blog. This is a great way to share information with your team and your
supporters.<b><a href=http://www.hzzxdq.net>power strip</a></b> |<b><a href=http://www.jdxpwj.cn/booster-cable>booster cable</a></b> |
<b><a href=http://www.jdxpwj.cn/tow-rope>tow rope</a></b> |<b><a href=http://www.jdxpwj.cn/ratchet-tiedown>ratchet tiedown</a></b>


56. lina Aug 23, 2010 at 23:30

What youre saying is completely true. I know that everybody must say the same thing, but I just think that you put it
in a way that everyone can understand. I also love the images you put in here. They fit so well with what youre trying to say.
Im sure youll reach so many people with what youve got to say.<b><a href=http://www.tygluegun.com>glue stick</a></b> |<b><a href=http://www.tygluegun.com>glue gun</a></b>
|<b><a href=http://www.wanjia-ylm.cn>booster cable</a></b> |<b><a href=http://www.wanjia-ylm.cn>power cord</a></b>


57. king Aug 23, 2010 at 23:38

Well done, I admire the valuable information you offer in your articles. I will bookmark your blog
and have my children check up here often. I am quite sure they will learn lots of new stuff here than
 anybody else<b><a href=http://www.hzhtdq.cn>power strip</a></b> |<b><a href=http://www.hzhtdq.cn>extension cord</a></b>
 |<b><a href=http://www.hzhtdq.cn>trouble light</a></b>


58. clothes store Aug 24, 2010 at 19:31

David Heinemeier Hansson..thanks


59. cheap nfl jerseys Aug 24, 2010 at 20:11

<a href="http://www.nfljerseyse.com/dallas-cowboys-jerseys " title="Dallas Cowboys Jerseys ">Dallas Cowboys Jerseys </a>


60. louis vuitton shoes Aug 26, 2010 at 23:14

Thanks for sharing your article. I really enjoyed it. I put a link to my site to here so other people can read it. My readers have about the same interets


61. five finger shoes Aug 27, 2010 at 23:30

good


62. mbt shoes sale Aug 28, 2010 at 09:46

have become a huge fan of this website and I really cant wait to read you next posts! I really enjoy watching the RailsCasts.


63. cheap mbt shoes Aug 28, 2010 at 10:08

I thought I would let you know that for some reason this blog does not display well in Internet Explorer 8. I wish Microsoft would stop changing their software. I have a question for you. Do you mind exchanging blog roll links? That would be really cool!


64. cheap ugg boots sale Aug 28, 2010 at 10:21

hope you’re always happy to share this every single day,thanks alot for your information, Air Jordan 1 I’ll bookmark this and share to all my friend for dropping at here, have a nice day… air jordan2 shoes,air force 1s


65. herve leger dress Aug 30, 2010 at 19:49

Thanks for sharing your article. I really enjoyed it. I put a link to my site to here so other people can read it.


66. snow boots Aug 30, 2010 at 20:21

but all of the past videos have been fine.


67. louis vuitton sunglasses Sep 01, 2010 at 22:19

Good post, I can’t say that I agree with everything that was said, but very good information overall:)


68. blu ray ripper Sep 02, 2010 at 00:22

This is really a nice guide for Newbies like me. Thank you.

Add your comment:

(SKIP THIS ONE)

(required)

(not shown)


(use pastie or gist for code)

sponsored by:
if you want to help:
required:
Get Quicktime Player
Give Back to Open Source