Forum: Ruby on Rails How does one validate a 'float' field?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Eab29c2bb9cd37cd30b7b3e1a35926b9?d=identicon&s=25 unknown (Guest)
on 2007-04-25 16:16
(Received via mailing list)
I would like to validate the following conditions on a numeric field:

1) That the user did not enter a non-numeric string where he was
required to enter a number.
2) That the numeric value is zero or greater.

There seems to be a conflict between these two requirements:

If the user enters a non-numeric string (e.g "ABC"), by the time it
reaches the validation function within the ActiveRecord object, it has
already been marshalled into a numeric format. "ABC" will be converted
to zero. According to condition #2, this is an acceptable value.
According to condition #1, it is not.

Is there anyway I can execute the validation methods on the raw string
values, before they are "casted" into the ActiveRecord types?
Otherwise, can you suggest an elegant solution for this problem?

Thanks!

Shimon Amit
72ea925c0ca3d19fdd2f12fa76681624?d=identicon&s=25 Stephan Wehner (stephanwehner)
on 2007-04-25 18:36
unknown wrote:
> I would like to validate the following conditions on a numeric field:
>
> 1) That the user did not enter a non-numeric string where he was
> required to enter a number.
> 2) That the numeric value is zero or greater.
>
> There seems to be a conflict between these two requirements:
>
> If the user enters a non-numeric string (e.g "ABC"), by the time it
> reaches the validation function within the ActiveRecord object, it has
> already been marshalled into a numeric format. "ABC" will be converted
> to zero. According to condition #2, this is an acceptable value.
> According to condition #1, it is not.
>
> Is there anyway I can execute the validation methods on the raw string
> values, before they are "casted" into the ActiveRecord types?
> Otherwise, can you suggest an elegant solution for this problem?
>
> Thanks!
>
> Shimon Amit

Look through

  http://ar.rubyonrails.com/classes/ActiveRecord/Base.html

for before_type_cast

But maybe you are really looking for  validates_numericality_of

Stephan
Eab29c2bb9cd37cd30b7b3e1a35926b9?d=identicon&s=25 unknown (Guest)
on 2007-04-25 20:31
(Received via mailing list)
Thank you. That is exactly what I was looking for.

Shimon Amit

On Apr 25, 7:36 pm, Stephan Wehner <rails-mailing-l...@andreas-s.net>
This topic is locked and can not be replied to.