66

When I'm giving input type number the letter e and special charecters are also displaying in input field. I want to display only digits. How to block them?

<input type="number">
Hitmands
  • 13,491
  • 4
  • 34
  • 69
Surya Teja
  • 1,388
  • 3
  • 16
  • 32
  • 1
    Are you using Angular in your project or you just mistyped the tag? – G07cha Sep 02 '16 at 12:05
  • 5
    `1e1` is a valid Number, that's [exponential notation](https://en.wikipedia.org/wiki/Scientific_notation#E_notation). – Aaron Sep 02 '16 at 12:05
  • 3
    @Aaron, you are right, but OP wants to display only numbers. – G07cha Sep 02 '16 at 12:06
  • And? It's both a valid "number" and "Number". Maybe he only want decimal digits? – Aaron Sep 02 '16 at 12:07
  • 1
    I'm surprised to see that `+` is allowed, but [it is](https://www.w3.org/TR/html5/infrastructure.html#valid-floating-point-number). – T.J. Crowder Sep 02 '16 at 12:08
  • 3
    I know 1e1 is a valid number...but i want to display only numbers between 0-9...is there any way to block them? – Surya Teja Sep 02 '16 at 12:08
  • http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery – mplungjan Sep 02 '16 at 12:09
  • Check this http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery – Hitesh Misro Sep 02 '16 at 12:09
  • 2
    This is not a duplicate of [*How to make type=“number” to positive numbers only*](http://stackoverflow.com/questions/19233415/how-to-make-type-number-to-positive-numbers-only). Those answers won't prevent scientific notation. *(One answer tries to, but it doesn't work.)* – T.J. Crowder Sep 02 '16 at 12:09
  • Look at this full answer with examples : http://stackoverflow.com/a/469362/1359623 – aprovent Sep 02 '16 at 12:17
  • The one I posted later did handle everything – mplungjan Sep 02 '16 at 12:24
  • The big issue is that pressing 'e' does not trigger any event (in number type inputs), so you can never check if the currently pressed key is an 'e'. Basically the only way, as far as I can tell, is to use a 'text' type input with a lot of custom validation. – paddotk Oct 13 '20 at 11:29

18 Answers18

52

Try preventing the default behaviour if you don't like the incoming key value:

document.querySelector(".your_class").addEventListener("keypress", function (evt) {
    if (evt.which != 8 && evt.which != 0 && evt.which < 48 || evt.which > 57)
    {
        evt.preventDefault();
    }
});

// 0 for null values
// 8 for backspace 
// 48-57 for 0-9 numbers
<input type="number" class="your_class">
Sidharth Gusain
  • 1,473
  • 1
  • 13
  • 20
48

A simple solution which I used in React.

onKeyDown={(evt) => ["e", "E", "+", "-"].includes(evt.key) && evt.preventDefault()}
msahin
  • 1,520
  • 1
  • 16
  • 22
37

You can block entering those chars with keydown event

var inputBox = document.getElementById("inputBox");

var invalidChars = [
  "-",
  "+",
  "e",
];

inputBox.addEventListener("keydown", function(e) {
  if (invalidChars.includes(e.key)) {
    e.preventDefault();
  }
});
<input type="number" id="inputBox" />

but the user can still enter them if s/he does a copy/paste (or through the console). To prevent copy/paste, you can do a replace on the entered value [*].

var inputBox = document.getElementById("inputBox");

var invalidChars = [
  "-",
  "+",
  "e",
];

inputBox.addEventListener("input", function() {
  this.value = this.value.replace(/[e\+\-]/gi, "");
});

inputBox.addEventListener("keydown", function(e) {
  if (invalidChars.includes(e.key)) {
    e.preventDefault();
  }
});
<input type="number" id="inputBox" />

* You can't really get the entered value on an input field with type set to number. You can get the entered value as long as it is a number, that is, the value passes the internal number check. If the user copy/paste 1e, suggested solution will fail.

What happens when you enter 1e is that, input field checks if it's a number, and if it's not (1e is not) it throws a warning:

The specified value "1e" is not a valid number. The value must match to the following regular expression: -?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?

and the value property is set to "".

If you check the field's properties, you'll find valueAsNumber property. If the entered value is a number, input field parses the value and stores it in valueAsNumber. Since 1e is not a number, it evaluates to NaN, and NaN is assigned to valueAsNumber and value is set to "". Though you still see 1e on the input field.

I've asked a question related to this problem, but no solution yet.

Get the entered value on number input field, not the parsed

Community
  • 1
  • 1
akinuri
  • 10,690
  • 10
  • 65
  • 102
12

Instead on trying to block values, you can try to replace values that are non numeric.

If you choose to handle keycodes, you will have to handle numKeys, numPad, shift +, crtl + etc and trying to refresh while focus is inside textbox will also fail. Prevent Default will stop lot more than incorrect values.

$("#input").on("input", function() {
  var nonNumReg = /[^0-9]/g
  $(this).val($(this).val().replace(nonNumReg, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="tel" id="input" />
<div class="alert"></div>
Rajesh
  • 24,354
  • 5
  • 48
  • 79
7

Following form from the answers above, most of the examples above cover it, i just noticed that when inputting "E" this is still allowable so i think its best to add this into the array. I am using Jquery 3.3.1 in this example.

Also that way whatever you enter into the array will be prevented from being keyed in into the input box

Note - take the 'elementid' as the id of the element you want to apply this to similarly if you want to apply this to all inputs that are type number in JQuery --> $("input[type='number']")

var invalidChars = ["-", "e", "+", "E"];

$("input[type='number']").on("keydown", function(e){ 
    if(invalidChars.includes(e.key)){
         e.preventDefault();
    }
}):

This sample above should work on all inputs with a type of number and prevent the characters "-", "e", "+" and "E" from being keyed into the input.

UPDATE

Just also notices that you are able to enter '.' as they represent decimal points which is valid for numbers. I was using this validating a telephone number and obviously (for UK) there is no '.' so that may also be another character to add to your array.

6

Here's a pretty concise solution using jQuery based on some of the other solutions:

$("input[type=number]").on("keydown", function(e) {
        var invalidChars = ["-", "+", "e"]; //include "." if you only want integers
        if (invalidChars.includes(e.key)) {
            e.preventDefault();
        }
});
5

You can check it if it's a number or not.

// Restrict e, -, + for html input number
$(document).on('keypress', ':input[type="number"]', function (e) {
    if (isNaN(e.key)) {
        return false;
    }
});
Joko Wandiro
  • 1,957
  • 1
  • 18
  • 28
4

You can do it easily using jQuery

Try this code

$(function() {
    $("#input").keypress(function(event) {
        if (event.which != 8 && event.which != 0 && (event.which < 48 || event.which > 57)) {
            $(".alert").html("Enter only digits!").show().fadeOut(2000);
            return false;
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="input" />
<div class="alert"></div>
Hitesh Misro
  • 3,397
  • 1
  • 21
  • 50
4
$("#input").on("input", function() {
  var nonNumReg = /[^0-9]/g
  $(this).val($(this).val().replace(nonNumReg, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="tel" id="input" />
<div class="alert"></div>
4

With onKeyUp, onKeyPress or onKeyDown events the same can be restricted.

onKeyDown = {
  (e) => ["e", "E", "+", "-"].includes(e.key) && e.preventDefault()
}
Zach Jensz
  • 3,650
  • 5
  • 15
  • 30
Anuaf
  • 41
  • 3
  • It works also in React js 17 and Typescript. `onKeyDown: (e: any) => ["e", "E", "+", "-", ".", ","].includes(e.key) && e.preventDefault(),`. – Elo Dec 16 '22 at 09:01
  • This won't work on Android phones though – MK. May 16 '23 at 16:54
2

Since OP's question was tagged with 'angularjs', the cleanest solution would probably be to use a directive. Several solutions for this approach have previously been explained here:

angularjs: allows only numbers to be typed into a text box

Community
  • 1
  • 1
dperish
  • 1,493
  • 16
  • 27
2

JQuery
You can also use the following code if you want to accept decimals(.)

$('input[Type="Number"]').keypress(function (e) {
    if ('0123456789'.indexOf(e.key)!=-1){}
    else if (e.key=='.' && this.value!='' && (this.value.match("\.") || []).length==0){}
    else{e.preventDefault();}
});

Nima
  • 323
  • 4
  • 13
2

Here is React solution, hope it will help somebody

const numberInputInvalidChars = ['-', '+', 'e'];

   <input
      type="number"
      onKeyDown={(e) => {
        if (numberInputInvalidChars.includes(e.key)) {
          e.preventDefault();
        }
      }}
    ></input>
1

Yo can Block by using some JQuery codes

 $('input[Type="Number"]').keypress(function (e) {
    if ('0123456789'.indexOf(e.key) == -1) {
        e.preventDefault();
    }
});

This will affect on all Numeric typed Input

Omid Farvid
  • 785
  • 7
  • 13
0

I'm not sure the details of your use case, but you may not need to do a lot to handle these yourself. For starters, you can set a min, which can be used to prevent negatives, as well as a max value and a step value if that's useful. It turns out the default step is 1, so it requires integers unless you specify a decimal step value.

When it comes to dealing with the "e" in numbers, you can use Number() to convert text to a number, and it'll automatically convert the "e", as well as any "+" sign:

> Number("5e3") 
5000
> Number("+42") 
42

If you really need the submitted value to be normalized, you can convert it back in place. I think probably the most user friendly time to do it would be on blur:

input.addEventListener('blur', () => {
  if (input.value !== '' && input.checkValidity()) {
    input.value = Number(input.value);
  }
});
lobati
  • 9,284
  • 5
  • 40
  • 61
0

in the input of numeric type the events for characters with value different from [0-9] is an object with

event.target.value: ""

so just prevent events that have no value

if (!event.target.value) {
  event.preventDefault();
};
EvoluWil
  • 111
  • 3
0

Here is a plain html/js solution which:

  1. Restricts input to digits, +, -, ., E, e (type="number")
  2. Then, prevents +, -, ., E, e from being registered in the input field (onkeydown="if (/^[eE.\+\-]$/.test(event.key)) event.preventDefault();")
  3. Also, prevents anything other than a string of digits from being pasted into the field (onPaste="if (!/^\d+$/.test(event.clipboardData.getData('text/plain'))) event.preventDefault();")
<input
  type="number"
  onkeydown="
    if (/^[eE.\+\-]$/.test(event.key))
      event.preventDefault();
  "
  onPaste="
    if (!/^\d+$/.test(event.clipboardData.getData('text/plain')))
      event.preventDefault();
  "
>

If you would also like to trim leading zeroes, you can add this:

oninput="
  return
    event.target.value.replace(/^0*/, '') || 
    '0';
"
biinster
  • 45
  • 9
-3

If you want + sign in your phone number field then you can use this code.

var inputBox = document.getElementById("inputBox");

var invalidChars = [
  "-",
  "e",
];

inputBox.addEventListener("keydown", function(e) {
  if (invalidChars.includes(e.key)) {
    e.preventDefault();
  }
});
<input type="number" id="inputBox" />