How do I validate a numeric field?


#1

Hello,

I have a quanity field in my form that should have a length of no more
than 3.

I tried validate_length_of :qty, :maximum => 3

and this fails

Thanks
Frank


#2

Frank,

try this:

validate_format_of :qty, /[1-9][\d]{0,2}/

That should get you a non-zero digit, followed by up to two more digits.

  • Jamie

#3

I get Application error (Rails)

Frank
----- Original Message -----
From: “Jamie M.” removed_email_address@domain.invalid
To: removed_email_address@domain.invalid
Sent: Thursday, December 08, 2005 4:27 PM
Subject: Re: [Rails] how do I validate a numeric field?


#4

Frank wrote:

I have a quanity field in my form that should have a length of no more than 3.

I tried validate_length_of :qty, :maximum => 3

and this fails

Numbers don’t have a length. Just because a numeric value is 1001
doesn’t mean the variable has a “length” of 4.

What you probably want to use is:

validates_inclusion_of :qty, :in => 0…999

-Brian


#5

I’m guessing, but is “length” meant for strings and it should be
something like validate_with_precision? something like that.

bruce


#6

Jamie M. wrote:

try this:

validate_format_of :qty, /[1-9][\d]{0,2}/

Just so we’re clear, the method is correctly named,
“validates_format_of”, not “validate_format_of”. At least, that’s what
my PDF copy of AWDwR says. But I wouldn’t use validates_format_of to
check for a number within a certain range of values. That’s what
validates_inclusion_of is for…

-Brian


#7

Sorry, validates_format_of (with an S). I like Brian’s answer better
though.


#8

Thanks,

This worked:

validates_inclusion_of :QTY1, :in => 0…999, :message => “must be
between 0
and 999”

Frank

----- Original Message -----
From: “Brian V. Hughes” removed_email_address@domain.invalid
To: removed_email_address@domain.invalid
Sent: Thursday, December 08, 2005 4:37 PM
Subject: Re: [Rails] how do I validate a numeric field?


#9

Hi Frank,

You could use the *validates_numericality_of(*args) *method.

eg
validates_numericality_of :qty, :only_integer => true
http://api.rubyonrails.com/classes/ActiveRecord/Validations/ClassMethods.html#M000690

Your model class can then include a validate method. This method is
called
before the model is saved, and you should protect it.

ie
protected
def validate
errors.add( :qty, “Should be between 0 and 1000”) unless ( :qty.nil?
||
(:qty >= 0 and :qty < 1000))
end

This information came from the Agile web Development with Rails book
modified for this situation. It is a great book when your starting with
Rails.

Cheers
Dan