Search code examples
javascriptreactjsvalidationinput

How to check If the value of an input is number or string in react js?


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 ?


Solution

  • The simplest way will be to convert the string to a number and then check if it's valid. As the value of inputs is always a string even if you use type="number", though it is good to use it if you 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