10

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?

Wulthan
  • 417
  • 2
  • 6
  • 19
  • 2
    Possible duplicate of [how do i block or restrict special characters from input fields with jquery?](http://stackoverflow.com/questions/895659/how-do-i-block-or-restrict-special-characters-from-input-fields-with-jquery) – elementzero23 Jan 18 '17 at 08:47
  • @elementzero23: This is not a jQuery question. – Nisse Engström Jan 22 '17 at 09:54
  • This is a really good question and I would hope W3C will come up with a HTML solution someday. – Turbo Dec 02 '17 at 01:28

3 Answers3

14

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">
Dani
  • 2,448
  • 8
  • 27
  • 44
2

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");
    }
});
Boris K
  • 1,469
  • 9
  • 29
0

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.

Andrew Stalker
  • 718
  • 5
  • 22