Create a Numbers only Input field in React.js

avatar
Borislav Hadzhiev

Last updated: Apr 6, 2024
4 min

banner

# Table of Contents

  1. Create a Numbers only Input field in React.js
  2. Check if an Input's value is a valid Number in React

# Create a Numbers only Input field in React.js

To create an input field with only numbers allowed in React.js:

  1. Set the type of the input field to text.
  2. Add an onChange event handler that removes all non-numeric values.
  3. Keep the input value in a state variable.

number only input

App.js
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;
The code for this article is available on GitHub

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.

NameDescription
regexpa regular expression we want to match in the string
replacementthe 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.

This means that if the string only contains non-digit characters we would replace all of them with empty strings and the String.replace method would return an empty string.

If you need to restrict an input field to only letters, check out the following article.

# Handling an empty input value

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.

App.js
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;

handling empty input value

The code for this article is available on GitHub

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.

# Using an 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.

App.js
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;
The code for this article is available on GitHub

Note that even though the input has its type set to number, its value is still of type string.

This approach also allows the user to enter values like e-123, which you might not want.

input type number

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.

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

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

  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 code for this article is available on GitHub

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.

App.js
<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.

App.js
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'); } };
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 doesn't contain only spaces.

App.js
function isNumber(str) { if (str.trim() === '') { return false; } return !isNaN(str); }
The code for this article is available on GitHub

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.

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev