70

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">

12
  • 1
    Are you using Angular in your project or you just mistyped the tag?
    – G07cha
    Sep 2, 2016 at 12:05
  • 5
    1e1 is a valid Number, that's exponential notation.
    – Aaron
    Sep 2, 2016 at 12:05
  • 3
    @Aaron, you are right, but OP wants to display only numbers.
    – G07cha
    Sep 2, 2016 at 12:06
  • 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 2, 2016 at 12:08
  • 2
    This is not a duplicate of 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.) Sep 2, 2016 at 12:09

18 Answers 18

56

A simple solution which I used in React.

onKeyDown={(evt) => ["e", "E", "+", "-"].includes(evt.key) && evt.preventDefault()}
3
  • 1
    Excellent, can be directly applied as an input attribute.
    – stefaleon
    Apr 20, 2022 at 18:01
  • good job brother, that worked for me thank you <3 Dec 13, 2022 at 16:57
  • That's work for me also in Next.js
    – HendyCrcs
    Nov 7 at 13:20
53

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">

5
  • 24
    user can still copy paste 12e.+-
    – GorvGoyl
    Nov 17, 2017 at 5:45
  • 2
    this will break min/max validation in html5 Dec 6, 2018 at 18:04
  • if (evt.which != 8 && evt.which != 46 && evt.which < 48 || evt.which > 57 || evt.key=='.') to prevent e.g. 12...34
    – Apogentus
    May 4, 2020 at 12:37
  • 1
    how to prevent copy paste 12e.+- –
    – huykon225
    Jan 10, 2022 at 9:24
  • If preventing copy paste is necessary, the better option may be to use input type text or tel like here or here
    – Kida
    Nov 8 at 8:21
38

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

3
  • 2
    @downvoter Will the downvoter care to explain his reason? I doubt that this answer is not useful.
    – akinuri
    Sep 3, 2016 at 12:29
  • 3
    Really nice solution, other answers looks like dirty tricks, or not useful. Vote up! Dec 28, 2017 at 16:04
  • you need to add "E" to invalidChars array because 'E' != 'e' Mar 16, 2022 at 10:36
13

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>

1
  • i guess he was expecting input type to be number (to get a spinner)
    – GorvGoyl
    Nov 17, 2017 at 6:35
8

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.

2
  • add "." to invalidChars to prevent inputs like 12...34
    – Apogentus
    May 4, 2020 at 12:47
  • I think you would still want the . for decimal types in a string May 4, 2020 at 12:49
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();
        }
});
0
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;
    }
});
1
  • 4
    this disables backspace, del, tab, enter
    – Que Dee
    Feb 18, 2021 at 22:09
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>

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>
1
  • 7
    This answer should contain some explanation. To post only a code snippet is not a good answer.
    – ochs.tobi
    Aug 8, 2018 at 6:18
4

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

onKeyDown = {
  (e) => ["e", "E", "+", "-"].includes(e.key) && e.preventDefault()
}
2
  • It works also in React js 17 and Typescript. onKeyDown: (e: any) => ["e", "E", "+", "-", ".", ","].includes(e.key) && e.preventDefault(),.
    – Elo
    Dec 16, 2022 at 9:01
  • This won't work on Android phones though
    – MK.
    May 16 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

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();}
});

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

1

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';
"
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);
  }
});
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();
};
-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" />

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.