Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJs prevent e and dot in an input type number

I would like to prevent e and . to be type in an <input type="number"/>. Without jQuery or using step attribute. I've tried with pattern="[0-9]" but it's not working.

EDIT : On focus the keyboard should be a digit keyboard.

like image 900
Philippe Avatar asked Aug 23 '17 08:08

Philippe


People also ask

How do you restrict negative values in input type numbers in react JS?

You can add an onKeyPress listener to the input element and that will be triggered before the onChange and call a function that will prevent default behaviour when the minus button is pressed. Note that this will still allow negative values to be pasted into the input.

Why does input type number allow e?

HTML input number type allows "e/E" because "e" stands for exponential which is a numeric symbol. Example 200000 can also be written as 2e5.


1 Answers

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:

<input type="number" onKeyDown={ (evt) => evt.key === 'e' && evt.preventDefault() } />
like image 67
Jeff C Avatar answered Oct 12 '22 14:10

Jeff C