Wednesday, March 14, 2007

Validate a number is an integer and within a certain range

Use validates_numericality_of , and validates_inclusion_of to check that a number is an integer and within a certain range.

For example:

You only want to allow people to enter a number between 21 and 30. Here is how you would do it.

validates_numericality_of :n, :only_integer => true, :message => "can only be whole number."
validates_inclusion_of :n, :in => 21..30, :message => "can only be between 21 and 30."

7 comments:

Hlacos said...

jeah

Anonymous said...

yeah

Anonymous said...

I am searching for an answer to my question, how do I get the :message that gets set in the validate_numericality_of to show in my view form when there are errors. its amazing that I cant find this one little answer. maybe its so obvious (to others) that it's not mentioned anywhere, so what is the answer?

Conrad said...

Andrew, did you try error_message_on and error_messages_for?

error_message_on
error_message_for

Anonymous said...

I just got the answer from a helpful person in IRC

<%= error_messages_for 'model_name_goes_here' %<

I spent some time trying to find the answer to this one.

the problem is there is no reference linking between classes in the railsapi

Anonymous said...

the last post should have this arrow on the right of the line: >

da Mata said...

Great help, thanks a lot!