dabadaba
dabadaba

Reputation: 9542

Validate number with rails 3

How can I validate if the input in a text field is a number? not_integer is not what I am looking for. It can be a decimal number.

Upvotes: 0

Views: 237

Answers (2)

Kirti Thorat
Kirti Thorat

Reputation: 53048

To restrict the user from entering non-numeric values at the form-level and avoid expensive server call just to check numericality.

Use this in the form:

<%= f.number_field :attribute_name, :step => 'any' %>

This will create an html element as below:

<input id="post_attribute_name" name="post[attribute_name]" step="any" type="number">

Upon form submission, the input value is checked at the form level. step = "any" will allow decimals.

I would also recommend adding validation at the Model level using,

validates :attribute_name, numericality: true  ## As suggested by Justin Wood

This way you have double protection, i.e., one at the form-level itself and the other at Model level.

Upvotes: 1

Justin Wood
Justin Wood

Reputation: 10061

You can check for numericality

validates :points, numericality: true

If you want a more general approach, you can use is_a?. The parent number class in Ruby is Numeric.

a = 4
a.is_a? Numeric
=> true

b = 5.4
b.is_a? Numeric?
=> true

c = "apple"
c.is_a? Numeric
=> false

d = "4"
d.is_a? Numeric
=> false

Upvotes: 4

Related Questions