Validation help

I would like to validate a number within a certain range.
To first test that a entry is a valid number i use
validates_numericality_of :my_number, :message =>‘sorry, not a number’

to test if the number is within a certain range i use
validates_inclusion of :my_number, :in => min…max, message => ‘outside
range!’

If the numericality test fails, I don’t want to do the second range
test, otherwise both error messages will be displayed. At the moment,
both tests with be performed regardless. Any ideas on how to do this?

Thanks.

What would happen if you just take off the validates_numericality_of,
and left only validates_inclusion?

I know about two ways to solve your problem:

a) you can define a validate method in your method, do the validations
by yourself, and if you found any error, you can add them to the array
errors, example:

def validate
if (price == nil)
errors.add “There is not price!!!”
else if (price < 0)
errors.add “The price is negative!!!”
end
end

b) You can check what errors to display, in the view, by inspecting
modelobject.errors

Rodrigo D.

Iplan Networks Datos Personales
[email protected] [email protected]
www.iplan.com.ar www.rorra.com.ar
5031-6303 15-5695-6027

-----Mensaje original-----
De: [email protected]
[mailto:[email protected]] En nombre de montyman
Enviado el: Miércoles, 21 de Junio de 2006 10:14 a.m.
Para: [email protected]
Asunto: [Rails] validation help

I would like to validate a number within a certain range.
To first test that a entry is a valid number i use
validates_numericality_of :my_number, :message =>‘sorry, not a number’

to test if the number is within a certain range i use
validates_inclusion of :my_number, :in => min…max, message => ‘outside
range!’

If the numericality test fails, I don’t want to do the second range
test, otherwise both error messages will be displayed. At the moment,
both tests with be performed regardless. Any ideas on how to do this?

Thanks.


Posted via http://www.ruby-forum.com/.


Rails mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails

Hey Monty, if you goal is to validate that a field is within a certain
range, then I would recommend using ‘validates_inclusion’.

-Conrad

thank you conrad for posting that tip!

Conrad T. wrote:

Hey Monty, if you goal is to validate that a field is within a certain
range, then I would recommend using ‘validates_inclusion’.

-Conrad

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs