Search code examples
ruby-on-rails-3validationform-helpers

Rails 3 - Make text field accept only numeric values


How do I make a text field accept only numeric values? If I press a letter or a symbol, the text field should not be filled, it should only allow numbers.

Is there a rails way to do this?


Solution

  • On the server side validate numericality:

    class SomeModel
      validates :some_column, :numericality => {:only_integer => true}
    end
    

    and on the client side, add an input mask via javascript https://github.com/ruoso/jquery-regex-mask-plugin

    $('#some_input').regexMask(/^\d+$/);