I am trying to avoid any type of string when entering an input. I found a code here on stack overflow which works. However it only works when a number is entered first, or if I put a letter and delete all; it does not work when typing the first letter. And I didn't understand the code that well. I don't even know what is /^[0-9\b]+$/
Here is the code
const [value, setValue] = useState();
const handleChange = (e) => {
const re = /^[0-9\b]+$/;
if (e.target.value === "" || re.test(e.target.value)) {
setValue(e.target.value);
}
};
How about testing if conversion to Number returns NaN? Try code below:
const [value, setValue] = useState();
const handleChange = (e) => {
if (!isNaN(Number(e.target.value))) {
setValue(e.target.value);
}
};
And, btw, as guys in the comments below the original question correctly pointed out, this: /^[0-9\b]+$/ is indeed a Regular Expression