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.
unknown (Guest)
on 2007-04-25 18: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 A.
Stephan W. (Guest)
on 2007-04-25 20: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 A.

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
unknown (Guest)
on 2007-04-25 22:31
(Received via mailing list)
Thank you. That is exactly what I was looking for.

Shimon A.

On Apr 25, 7:36 pm, Stephan W. <removed_email_address@domain.invalid>
This topic is locked and can not be replied to.