How to block +,-,e in input type Number?
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
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">