What's New in Edge Rails: validates_numericality_of Gets Pimped

Posted by ryan
at 6:54 PM on Tuesday, May 29, 2007



validates_numericality_of just got a shot of mojo this weekend in the form of some highly useful options.

Prior to this recent change, your numerical validation options were limited to only_integer and allow_nil. Any desires to do anything slightly more complex meant dropping down into your own validation routine. Now, some of the more common validations one might want on a number parameter have been option-ized, including:
  • greater_than
  • greater_than_or_equal_to
  • equal_to
  • less_than
  • less_than_or_equal_to
  • odd
  • even

Which allows us to do things such as:

1
2
3
4
validates_numericality_of :salary, :greater_than_or_equal_to => 40000
validates_numericality_of :ten, :equal_to => 10
validates_numericality_of :bonus, :less_than => 5000
validates_numericality_of :prime, :odd => true

So put away that crusty custom validate and plug into these fresh validation options. Guaranteed to make your life easier.

tags: ruby, rubyonrails

Comments

Leave a response

  1. EricMay 30, 2007 @ 06:17 AM

    Nice!

    what about :between => (1970..2038) or :outside => (-10..10) ?

  2. Curtis MillerMay 30, 2007 @ 03:48 PM

    Hey, what about the only even prime, 2? ;) Seriously though, this is a cool addition to validates_numericality_of.

    @Eric: I think the first condition can be met using what is provided. The options are stackable, like:

    validates_numericality_of :foo, :greater_than_or_equal_to => 1970, :less_than_or_equal_to => 2038

    However, outside the range cannot be done, from what I can see. Maybe it would be helpful to add some of the range options (:is, :in, :within, :minimum, :maximum). This might also lend to consistency of terms.

  3. ckDecember 09, 2007 @ 06:18 AM

    Try this?

    validates_inclusion_of :foo, :in => 50..100, :message => “Die Bewertung muss zwischen 50 und 100 liegen”