The problem with type="number"
and min="1"
is that it allows typing or pasting the -
sign, the e
sign and the +
sign.
The problem with the Math.abs(value)
is that it replaces the whole typed in number with 0
, which we don't want and is very frustrating.
The e.keyCode
is very unreadable and deprecated.
The pure HTML method doesn't work in this case, you have to use JavaScript.
Remove the type="number"
and do this:
function inputNumberAbs() {
var input = document.getElementsByTagName("input")[0];
var val = input.value;
val = val.replace(/^0+|[^\d.]/g, '');
input.value = val;
}
<input oninput="inputNumberAbs()">
Regex explanation:
^0+
removes all 0s from beginning
|
OR operator
[^\d.]
remove everything that is ^
(NOT) a \d
(NUMBER) or a
.
(PERIOD)
This prevents the user to type or paste any of the not defined characters, like e, -, +,
and all other characters that are not numbers.
If you don't need decimal numbers just remove .
from regex.