Hello,
I want to simply check if a returned value from a form text field is a number i.e, 12 , 12.5, 12.75
is there a simple way to check, especially if the value is pulled as a param.
Thank you
Hello,
I want to simply check if a returned value from a form text field is a number i.e, 12 , 12.5, 12.75
is there a simple way to check, especially if the value is pulled as a param.
Thank you
You can use
12.is_a? Fixnum
(Fixnum
will work for ints and floats.)
If it arrives as a string that might contain a representation of a valid number, you could use
class String
def valid_float?
true if Float self rescue false
end
end
and then '12'.valid_float?
will return true if you can convert the string to a valid float (e.g. with to_f
).
You can add a:
validates_numericality_of :the_field
in your model.
See: http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M002172
Just regexp it, it's trivial, and not worth thinking about beyond that:
v =~ /^[-+]?[0-9]*\.?[0-9]+$/