1

I am having a bit of a hard time figuring out how to only allow user to input numbers 0-9 in an <input type="number" /> as it also allwos other things like eE.+ - etc..

Looked at regex solutions here on stack overflow and each one seems to have an issue i.e. if there are no numbers in an input you can type in any of unwanted characters, if you typed in a number you can't delete it completely as there needs to be at least 1 digit.

using keycodes introduces an issue as event.target.value is not avaliable on key events, it seems to only be available in onchange, however in this case e.which is not avaliable to check key pressed.

Ilja
  • 44,142
  • 92
  • 275
  • 498

3 Answers3

2

Do you mean you only want users to be able to enter digits 0-9?

var input = document.getElementById("only-digits");
input.onkeydown = function(e) {
  if (48 > e.which || e.which > 57)
    if (e.key.length === 1)
      e.preventDefault();
};
<input type="number" id="only-digits">

I'm making sure that the key the user presses is only a 0, 1, 2, ... 9 character using the range of their ASCII values.

If the key they pressed was outside of that range, then I make sure it is a word character and then I prevent it from being entered into the text field.

Community
  • 1
  • 1
theonlygusti
  • 11,032
  • 11
  • 64
  • 119
  • This prevents the user from deleting numbers, pressing return or tabbing to another input. – MT0 Jan 18 '17 at 10:01
  • Not my downvote but I still can't tab away from the input or use the backspace key to delete characters (Chrome 54) – MT0 Jan 18 '17 at 11:25
  • Now it allows multiple `.` characters. – MT0 Jan 18 '17 at 11:40
0

you can use the regex attribute on the html input field:

<input pattern="[0-9]*">

this allows only for 0-9 characters, zero or multiple times

<input pattern="[0-9]+">

this allows only for 0-9 characters, 1 or multiple times

update

it doesn't work with type="number" though, if you want it to work with this, you need to use javascript. See the other answers for this.

Community
  • 1
  • 1
Joel Harkes
  • 10,975
  • 3
  • 46
  • 65
0

You can prevent user when he/she enters any character other than Number

See the below code HTML

<input type=number class="numberOnlyInput" oncopy="return false" onpaste="return false" ondrag="return false">

JQuery

$(document).on('keypress','.numberOnlyInput',function(e){
  if(!(e.keyCode >=48 && e.keyCode <=57) ){
        e.preventDefault();
  }
});

You can see the demo here: https://jsfiddle.net/cnosh74e/

kapilpatwa93
  • 4,111
  • 2
  • 13
  • 22