John Smith
John Smith

Reputation: 6259

Validate only numbers

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

Answers (2)

mechnicov
mechnicov

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

Eric Duminil
Eric Duminil

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

Related Questions