Tejogol
Tejogol

Reputation: 720

React Input type="number" fields don't trigger onChange

I have added <input type="number" value={value} onChange={onChange}> to a form and am checking the format of the input using a simplified onChange function as illustrated in the following component:

  export function App() {
    const [value, setValue] = useState("");

    const onChange = (event) => {
      console.log("onChange called", event.target.value);
      setValue(event.target.value);
    };

    return <input type="number" value={value} onChange={onChange} />;
 }

I would like restrict the value of the input to only be integers using validation in the onChange function.

However, before I can add the validation, I noticed that when a user enters a valid non-integer number input, such as ., e or E, the value of the input is not passed to the onChange function, and hence I'm not able to perform my validation.

Below is a codesandbox that can be used to reproduce the issue.

 Example

What is the best way to add validation to an input field to ensure that the input is a whole number?

Upvotes: 3

Views: 5406

Answers (1)

Randall
Randall

Reputation: 2858

The e is the only letter that's accepted in a number field because it allows for exponents. You could use input type="text" but it doesn't give you the browser's native up and down arrows that type="number" does. And the pattern attribute validates on submission but doesn't stop someone from typing the 'e' in the first place. In React you can use this to completely block the 'e' key from being typed in a number input:

const [symbolsArr] = useState(["e", "E", "+", "-", "."]);
  return (
    <div className="App">
      <input
        type="number"
        onKeyDown={e => symbolsArr.includes(e.key) && e.preventDefault()}
      />
    </div>
  );

Codesandbox Demo

Upvotes: 3

Related Questions