最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

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 ?

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 ?

Share Improve this question edited Jun 16, 2021 at 18:08 Samathingamajig 13.2k3 gold badges17 silver badges44 bronze badges asked Jun 16, 2021 at 18:02 user12653085user12653085 3
  • the value of a <input> tag with type="text" will always have the type string for the value prop – Samathingamajig Commented Jun 16, 2021 at 18:05
  • @Samathingamajig I don't want to use type number for some reason is there any other way to check the value type ? – user12653085 Commented Jun 16, 2021 at 18:07
  • @Samathingamajig Even if u use type="number", the value of the input will be a string. – Manas Khandelwal Commented Jun 16, 2021 at 18:15
Add a comment  | 

3 Answers 3

Reset to default 15

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

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

you can check simply by comparing with typeof

  1. typeof Value === "string"
  2. typeof Value === "number"
发布评论

评论列表(0)

  1. 暂无评论