1

I want to check if the value of a type text input is number or string like this :

<input
  type="text"
  onChange={(e) => {
  const value = e.target.value;
    console.log(typeof value);
  }}
/>

But when I type text or number it console logs string in both cases .

How can I check if the value is number with input type text in react js ?

Samathingamajig
  • 5,615
  • 2
  • 11
  • 30

3 Answers3

4

The simplest way will be to convert the string to a number and then check if its valid. As the value of inputs is always a string even if u use type="number", tho it is good to use it if u just want numbers as the input.

You can use isNaN(+value). Here + will convert a string to a number.

<input
  type="text"
  onChange={(e) => {
    const value = e.target.value;
    console.log(!isNaN(+value)); // true if its a number, false if not
  }}
/>;

Some test cases:

console.log(!isNaN(+"54"));
console.log(!isNaN(+"23xede"));
console.log(!isNaN(+"test"));

Note: As mentioned this is a simple way, there can be workarounds to bypass this, for a robust solution you can have a look here: Check whether variable is number or string in JavaScript

Manas Khandelwal
  • 3,515
  • 2
  • 10
  • 22
0

You can cast to number and then check if it's Nan

isNaN(parseInt('0')) // false
isNaN(parseInt('f')) // true

As noted in the comments parseInt() will return a number for a string with a number in it. Using Number on the other hand will return Nan

isNaN(Number('55')) // false
isNaN(Number('55bob')) // true
Moshe Sommers
  • 1,288
  • 6
  • 11
-1

Because it is an input element’s value property (and since you only retrieved this value once, it retains the initial value - the empty string. If you want to check whether it is a number, you can try this:

function isNumber() { 
var val = document.getElementById("disc_perc1").value; 
var num = +value; 
if (num == num) { 
    alert("It is a number!"); 
} else { 
    alert("Uh, oh"); 
} 

}

Damon
  • 1
  • 2