Borislav Hadzhiev
Mon Apr 25 2022·2 min read
Photo by Raychan
To check if an input's value is a valid number in React:
isNaN()
function.isNaN
returns false
, the value is a valid number.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> ); }
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.
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
.
console.log(isNaN('hello')); // 👉️ true console.log(isNaN('')); // 👉️ false console.log(isNaN(' ')); // 👉️ false
isNaN
function converts an empty string or a string containing spaces to a number and gets a value of 0
, so it returns false
.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.
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.