14

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?

tee
  • 4,149
  • 1
  • 32
  • 44
Angelo
  • 905
  • 1
  • 17
  • 35

3 Answers3

36

Use number_field_tag, this will generate a HTML5 number field

http://apidock.com/rails/ActionView/Helpers/FormTagHelper/number_field_tag

Thong Kuah
  • 3,263
  • 2
  • 19
  • 29
  • Here's how you hide the steppers in webkit based browsers. http://stackoverflow.com/a/4812443/902968 – Keith Smiley Apr 20 '14 at 20:55
  • Unfortunately HTML5 number fields are broken in some browsers. If you type a non-numeric char, it *will* display it, and adding injury to insult, it will set the value to *blank*, so your JS and/or server won't even see what the user typed in. See https://code.google.com/p/chromium/issues/detail?id=304455 and https://github.com/angular/angular.js/issues/2144 – AlexChaffee Jun 02 '15 at 18:08
21

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+$/);
clyfe
  • 23,695
  • 8
  • 85
  • 109
1

@clyfe's answer is good, but that plugin doesn't work with HTML5 type=number elements. Here's some quick jQuery code that only allows integers:

  $("input[type=number]").keypress(function(event) {
      if (!event.charCode) return true;          
      ch = String.fromCharCode(event.charCode);
      return (/[\d]/.test(ch));
  });

to allow decimals or commas, make the regex look more like those in the plugin, e.g. https://github.com/ruoso/jquery-regex-mask-plugin/blob/master/regex-mask-plugin.js#L8 :

/^((\d{1,3}(\,\d{3})*(((\,\d{0,2}))|((\.\d*)?)))|(\d+(\.\d*)?))$/

(Note that different locales have different conventions for decimals and commas, so it's probably safer to just allow digits :-)

Note also that this is a workaround for the Chrome bugs mentioned here:

AlexChaffee
  • 8,092
  • 2
  • 49
  • 55
  • 1
    I asked this question 4 years ago and @clyfe's answer was what I needed... maybe your answer is usefull for people working now with rails and html5 – Angelo Jun 02 '15 at 21:28