Reputation: 6259
In one of my rails models I have this :only_integer
validation:
validates :number, presence: true, numericality: { only_integer: true }
This validation also allows inputs like +82938434
with +
-signs.
Which validation should I use to only allow inputs without +
-
only numbers?
Upvotes: 12
Views: 17424
Reputation: 15248
Rails 7 added :only_numeric
option to numericality
validator
validates :age, numericality: { only_numeric: true }
User.create(age: "30") # failure
User.create(age: 30) # success
Upvotes: 6
Reputation: 54223
The documentation for only_integer
mentions this regex :
/\A[+-]?\d+\z/
It means you could just use:
validates :number, format: { with: /\A\d+\z/, message: "Integer only. No sign allowed." }
Upvotes: 20