Ilja
Ilja

Reputation: 46479

Only allowing 0-9 numbers in input type="number" (exlude eE.+- etc..)

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.

Upvotes: 1

Views: 5198

Answers (3)

user3310334
user3310334

Reputation:

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.

Upvotes: 2

kapilpatwa93
kapilpatwa93

Reputation: 4411

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/

Upvotes: 1

Joel Harkes
Joel Harkes

Reputation: 11661

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.

Upvotes: 0

Related Questions