Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I restrict "+ - e , ." from HTML number input?

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?

like image 592
Wulthan Avatar asked Jan 18 '17 08:01

Wulthan


2 Answers

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">
like image 143
Dani Avatar answered Oct 24 '22 12:10

Dani


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");
    }
});
like image 27
Boris K Avatar answered Oct 24 '22 12:10

Boris K