Problem
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.
Workaround
The solution is to use and type="text"
type="number"
The solution starts with onkeypress
event.preventDefault()
and setting event.returnValue = false;
on invalid input, thus ensuring the input value is a number (float or integer). The following contains our javascript snippet for the onkeypress
handler:
When 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 /^[-]?[0-9]*\.?[0-9]*$/
- Allows negatives. You can start typing
just -
and it will be valid. - Allows one decimal point. You can start
typing 1234.
and that would be valid. Hopefully, once you parse the value, you do somethinglike Number.parseFloat("1234.")
which resultsin 1234
.
That’s it!
Next Steps
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.