How to check if user input is a number?

Viewed 2443

I would like to check if user input is a number; the 'input' is from an html input tag. I have provided code below. I don't understand why my code is not working, any help would be greatly appreciated.

document.getElementById('input').addEventListener("input",
function(){
  var userInput = document.getElementById('input').value;
  if(!isNaN(userInput)){
    alert("Is a number");
  }
  else{
    alert("Is not a number");
  }

},true);
User Input : <input id="input">

5 Answers

you can use typeof

var userInput = document.getElementById('input').value;
if(typeof userInput == 'number')){
  console.log("Is a number");
}else{
  console.log("Is not a number");
}

Try it like this.

function validate(){
  var userInput = document.getElementById('input').value;
  if(!isNaN(userInput)){
    console.log("Is a number");
  }else{
    console.log("Is not a number");
  }
}
<html>
<body>
<input type="text" id="input" onchange="validate()">
</body>
</html>

Many good answers already here, but another way I can think is to compare the string with 0 like following

"string" >= 0 || "string" <= 0

This return true only if its a number. But the catch is that it will also return true if its an empty string. So you can use if you know for sure that user enters at least one character/number or you are already handling the empty input case.

<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'>

accept only numbers.

You can use typeof to validate.

> a = 10
10
> typeof a
'number'

> if(typeof a === 'number') { console.log("Number") } else { console.log("Not a Number") }
Number
undefined
>
Related