Rails 3 - Make text field accept only numeric values
Asked Answered
T

3

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?

Thanh answered 12/12, 2011 at 21:29 Comment(0)
S
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+$/);
Statocyst answered 12/12, 2011 at 21:35 Comment(0)
E
36

Use number_field_tag, this will generate a HTML5 number field

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

Estabrook answered 12/12, 2011 at 22:25 Comment(2)
Here's how you hide the steppers in webkit based browsers. https://mcmap.net/q/126565/-disable-webkit-39-s-spin-buttons-on-input-type-quot-number-quotLisandra
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 code.google.com/p/chromium/issues/detail?id=304455 and github.com/angular/angular.js/issues/2144Streeter
S
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+$/);
Statocyst answered 12/12, 2011 at 21:35 Comment(0)
S
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:

Streeter answered 2/6, 2015 at 18:29 Comment(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 html5Thanh

© 2022 - 2024 — McMap. All rights reserved.