We recently hit a problem where users pasting large numbers in a
<input type="number"/> (part of a query input box), causing a wrong result. After further investigation, we realized that numbers (integer or floating points) exceeding 2^51 causes problems in Firefox, and probably just a bigger precision would cause problems in chrome.
At the time of this writing, the latest stable firefox is 60.5.1, and opening the snippet below in that browser rounds 0.060693571726285485 to 0.0606935717262855.
If this is a problem, then your project/organization requires you to work with these big of a precision. An unusual use case considering no UI framework libraries out there polyfills this problem. I tried so hard searching, and can’t find anything.
The solution is to use and
The solution starts with
event.preventDefault() and setting
onkeypress is called,
let inputTextValue = theEvent.srcElement.value; contains the current input text value without the just clicked key value, hence we concatenate them.
After the concatenation, we apply the regex test. Our regex
- Allows negatives. You can start typing
andit will be valid.
- Allows one decimal point. You can start
andthat would be valid. Hopefully, once you parse the value, you do something like
This solution is very simple but it’s missing a couple of things. For instance, it can’t take a step and spinner parameters. I will explore these avenues next time. I doubt we can stick to a native solution like this time, but we’ll see. Chances are, we’ll use UI frameworks, like angular/react to make those extra UI elements easier to play with.