Search code examples
ruby-on-railsruby-on-rails-3validationruby-on-rails-4

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?


Solution

  • 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." }