I’ve created a currency converter app. My app accepts number as input and works well. However, when user types something other than a number or leaves the input field empty, my app does nothing. I want it to return an error notice clarifying that providing a number is required.
This is my current code but it doesn’t work. It even doesn’t throw an error on the console but tries fetching as if number is provided.
input.js:
import React, { useState } from 'react';
const Input = ({ dropdown, onChange, label, symbols }) => {
const arrOfSymbols = Object.keys(symbols);
arrOfSymbols.sort();
const [error, setError] = useState('');
const handleInputChange = (e) => {
const inputValue = e.target.value;
console.log('Input Value:', inputValue);
// Check if the input is empty or not a number
if (inputValue.trim() === '' || isNaN(inputValue)) {
// Set the error state
setError('Please enter a valid number.');
console.log('Error:', 'Please enter a valid number.');
} else {
// If the input is valid, clear the error state
setError('');
// Proceed with the provided onChange callback
onChange(inputValue);
}
};
Input field on input.js:
<input type="number" placeholder="Enter the number you want to convert" className="px-4 py-2 rounded-xl" onChange={handleInputChange} />
Fetching part of index.js:
// FETCH
const convertCurrency = () => {
const options = {
method: "GET",
url: "http://localhost:3000/api/convert",
params: { convertFrom, convertTo, amount },
};
axios.request(options).then(function (response) {
const { data } = response;
setConvertedAmount((data.result));
setError(null); // Clear any previous errors
}).catch(function (error) {
console.error(error);
setError('An error occurred during conversion.'); // Set an error message
});
};
What my console throws when I click on Convert button (triggers convertCurrency function above) while input field is either blank or non-numeric:
GET http://localhost:3000/api/convert?convertFrom=ANG&convertTo=ANG&amount=
2
Answers
The first mistake you are making is using
isNaN()
to determine whether the input is a number or not. As you can read following the above link, it’s to be used to detect if a value equalNaN
, not any number.I would use a regular expression to avoid conversion before validation, because
e.target.value
comes as a string even if the type of the input isnumber
:Second, you would want to use
onInput
instead ofonChange
(which triggers only after the input looses focus, and on Safari it doesn’t if a non-number value is in the field):To check if a value is a real, finite number, use Number.isFinite()
Very simple, very elegant.
Number.isFinite() returns true only if the value is a number that’s not infinity or NaN. It’s a straightforward and reliable way to ensure you’re working with a valid number.
For more details, check out the MDN docs: Number.isFinite() on MDN