Categories
React Answers

How to prevent e and dot in an input type number with React?

Spread the love

To prevent e and dot in an input type number with React, we can validate the input value in the onChange prop function.

For instance, we write

const C = () => {
  //...
  const [val, setVal] = useState("");
  return (
    <div className="App">
      <input
        type="text"
        value={val}
        onChange={(e) => setVal(e.target.value.replace(/[^0-9]/g, ""))}
      />
    </div>
  );
};

to set the onChange prop to a function that replaces non number values with empty strings before call setVal with the string returned by replace that removes all the non digit characters in the input value.

Then we set value to val to show the input value without non digit characters.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *