Last updated: Apr 6, 2024
Reading timeยท4 min
To create an input field with only numbers allowed in React.js:
text
.onChange
event handler that removes all non-numeric values.import {useState} from 'react'; const App = () => { const [value, setValue] = useState(''); const handleChange = event => { const result = event.target.value.replace(/\D/g, ''); setValue(result); }; console.log(value); console.log(typeof value); console.log(Number(value)); return ( <div> <div>!Hello 123 World 456?___</div> <input type="text" placeholder="Your fav number" value={value} onChange={handleChange} /> </div> ); }; export default App;
We used the useState hook to keep track of the input field's value.
Every time the input's value is changed, the handleChange
function is
triggered.
We passed the following 2 arguments to the String.replace() method to remove all non-digit characters.
Name | Description |
---|---|
regexp | a regular expression we want to match in the string |
replacement | the replacement for each match |
The \D
character matches a character that is NOT a digit.
We added the g
(global) flag to match all non-digit characters and replace
them with an empty string.
String.replace
method would return an empty string.If you need to restrict an input field to only letters, check out the following article.
You might have to handle the scenario where the user doesn't enter any numbers into the input field.
Then the state variable would be an empty string and you might not want to
convert an empty string to a number because you'd get 0
.
import {useState} from 'react'; const App = () => { const [value, setValue] = useState(''); const handleChange = event => { const result = event.target.value.replace(/\D/g, ''); setValue(result); }; console.log(value); console.log(typeof value); console.log(Number(value)); // ๐๏ธ validation if (value !== '') { const num = Number(value); // ๐๏ธ submit form } return ( <div> <div>!Hello 123 World 456?___</div> <input type="text" placeholder="Your fav number" value={value} onChange={handleChange} /> </div> ); }; export default App;
You can make sure that the input doesn't store an empty string value and then convert the value to a number.
I've also written an article on how to set a character limit on an input field.
input
field of type number
Alternatively, you can use an input type number
, but that would allow the user
to enter characters like e
, -
, .
, etc.
import {useState} from 'react'; const App = () => { const [value, setValue] = useState(''); const handleChange = event => { setValue(event.target.value); }; console.log(value); console.log(typeof value); console.log(Number(value)); return ( <div> <div>.Hello- 123 World 456?___</div> <input type="number" placeholder="Your fav number" value={value} onChange={handleChange} /> </div> ); }; export default App;
Note that even though the input has its type
set to number
, its value is
still of type string
.
e-123
, which you might not want.In general, I'd advise against using this approach as it's much more
browser-dependent. Different browsers might handle an input type number
differently.
To check if an input's value is a valid number:
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.
<input id="num" name="num" type="text" onChange={handleChange} value={num} />
In our handleChange()
function, we update the num
state variable and check
if the value is a valid number.
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'); } };
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
doesn't contain only spaces.
function isNumber(str) { if (str.trim() === '') { return false; } return !isNaN(str); }
Then, we use the isNaN() function to check if the provided string is not a number.
We used 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.
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.