How to block +,-,e in input type Number?

JavascriptHtmlAngularjs

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

A simple solution which I used in React.

onKeyDown={(evt) => ["e", "E", "+", "-"].includes(evt.key) && evt.preventDefault()}

Solution 4 - Javascript

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>

Solution 5 - Javascript

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.

Solution 6 - Javascript

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

Solution 7 - Javascript

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>

Solution 8 - Javascript

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

Solution 9 - Javascript

$("#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>

Solution 10 - Javascript

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:

https://stackoverflow.com/questions/16091218/angularjs-allows-only-numbers-to-be-typed-into-a-text-box

Solution 11 - Javascript

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

Solution 12 - Javascript

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

Solution 13 - Javascript

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

Solution 14 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSurya TejaView Question on Stackoverflow
Solution 1 - JavascriptSidharth GusainView Answer on Stackoverflow
Solution 2 - JavascriptakinuriView Answer on Stackoverflow
Solution 3 - JavascriptmsahinView Answer on Stackoverflow
Solution 4 - JavascriptRajeshView Answer on Stackoverflow
Solution 5 - JavascriptCallistus AsirvathamView Answer on Stackoverflow
Solution 6 - JavascriptspencerdouglasView Answer on Stackoverflow
Solution 7 - JavascriptHitesh MisroView Answer on Stackoverflow
Solution 8 - JavascriptJoko WandiroView Answer on Stackoverflow
Solution 9 - JavascriptPrins Kumar GuptaView Answer on Stackoverflow
Solution 10 - JavascriptdperishView Answer on Stackoverflow
Solution 11 - JavascriptNimaView Answer on Stackoverflow
Solution 12 - JavascriptOmid FarvidView Answer on Stackoverflow
Solution 13 - JavascriptlobatiView Answer on Stackoverflow
Solution 14 - JavascriptTechnical ThingsView Answer on Stackoverflow