Check if an Input's value is a valid Number in React

avatar

Borislav Hadzhiev

Mon Apr 25 20222 min read

banner

Photo by Raychan

Check if an Input's value is a valid Number in React #

To check if an input's value is a valid number in React:

  1. Check if the input's value is not an empty string or contains only spaces.
  2. Pass the value to the isNaN() function.
  3. If isNaN returns false, the value is a valid number.
App.js
import {useState} from 'react'; function isNumber(str) { if (str.trim() === '') { return false; } return !isNaN(str); } export default function App() { const [num, setNum] = useState(''); const handleChange = event => { setNum(event.target.value); if (isNumber(event.target.value)) { console.log('✅ It is a valid number'); } else { console.log('⛔️ It is NOT a valid number'); } }; return ( <div> <input id="num" name="num" type="text" onChange={handleChange} value={num} /> </div> ); }

check if input valid number

The example shows how to check if the value of the input field is a valid number.

We set the onChange prop on the input field, so every time its value changes, the handleChange function is invoked.

In our handleChange function, we update the num state variable and check if the value is a valid number.

Note that the value of the input field is always going to have a type of string, regardless if its type prop is set to text or number.

In our isNumber function, we check if the passed in string is not empty and does not contain only spaces.

Then, we use the isNaN function to check if the provided string is not a number.

We use the logical NOT (!) operator to negate the value returned from the isNaN function.

The isNaN (is not a number) function tries to convert the string into a number and if it fails, it returns true.

index.js
console.log(isNaN('hello')); // 👉️ true console.log(isNaN('')); // 👉️ false console.log(isNaN(' ')); // 👉️ false
This seems quite confusing at first, but the isNaN function converts an empty string or a string containing spaces to a number and gets a value of 0, so it returns false.
index.js
console.log(Number('')); // 👉️ 0 console.log(Number(' ')); // 👉️ 0

This is why we use the trim() method to trim the string and verify that it's not an empty string.

We know that if the isNaN function gets called with a string that contains at least 1 character and returns true, then the string is NOT a valid number.

Conversely, if the isNaN function gets called with a string that contains at least 1 character and returns false, then the string is a valid number.

Alternatively, you can use a regular expression to only allow the user to enter numbers in your input field.

If you want to create an input field that only allows numbers, check out my other article - Create a Numbers only Input field in React.

Use the search field on my Home Page to filter through my more than 1,000 articles.