3

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?

1
  • 1
    That's the whole purpose of putting type='number' as an attribute in your input field. HTML does that for you. The browser solves that for you. Why do you need to validate yourself? Commented Sep 30, 2020 at 13:26

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

5 Comments

when I add console.log on onKeyDown nothing happends
@AljohnYamaro copy codesandbox link and see in demo. Everything work.
I recheck the demo and it works, apology I will update my down to upvote
can't update says "You last voted on this answer 8 hours ago. Your vote is now locked in unless this answer is edited."
This doesn't work on copy paste, drag and drop etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.