I've got a HTML number input element: <input type="number">
.
Problem is that I can also input following characters: + - e E , .
which I don't want the user to be able to write.
How do I restrict these?
I've got a HTML number input element: <input type="number">
.
Problem is that I can also input following characters: + - e E , .
which I don't want the user to be able to write.
How do I restrict these?
Edit: Boris K has got an even better answer.
Original answer:
This would be a way to accomplish that:
var ageInput = document.getElementById("age")
ageInput.addEventListener("keydown", function(e) {
// prevent: "e", "=", ",", "-", "."
if ([69, 187, 188, 189, 190].includes(e.keyCode)) {
e.preventDefault();
}
})
<input type="number" id="age">
You shouldn't rely only on <input type="number">
, because that would work only in moderns browsers with different behaviours depending on the browser.
Use jQuery to perform additional checks (with a regexp):
$('#my-input').keypress(function() {
var inputValue = $(this).val();
var reg = /^\d+$/;
if (reg.test(inputValue)){
alert("input value is integer");
} else {
alert("input value is not an integer");
}
});
To restrict those values, catch the keypress event with javascript, and prevent those characters from being entered. We capture the keyCode from the event, and restrict the input to not allow those characters by their ASCII codes.
document.getElementById('my-number-input').onkeypress = function(e) {
if(!e) e = window.event;
var keyCode = e.keyCode || e.which;
if(!((keyCode >= 48 && keyCode <= 57) ||
(keyCode >=96 && keyCode <= 105))) {
e.preventDefault(); //This stops the character being entered.
}
}
The IF statement above states that if the keycode is not in the range of 0-9 on the keyboard (including the number pad), then do not add the character to the input.