Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 input type number reformats long number

Tags:

html

I have an application whereby a user has to input a minimum of 15 digits in a number type textbox.

If a user enters a longer number, sometimes >= 19 digits, and then either uses the arrows on the right or the arrow keys on their keyboard, it autoformats the number to a float with e+ at the end which, obviously, isn't ideal.

<input min="0" type="number" value="7897894561234567898">

What's the best way to either remove or counteract this behaviour? Is there anything to be done, or will I have to use a text type input? (I'd rather not).

like image 506
G.Hunt Avatar asked Sep 15 '17 14:09

G.Hunt


1 Answers

The HTML5 <input type=number> specifically uses the same Number type as JavaScript. The maximum integer value before precision is lost is 9007199254740991, which has 16 digits.

You can't handle larger integers than that as a Number in JavaScript, you have to treat it as a string.

You should use <input type=text>, along with a pattern attribute for validation, and an inputmode attribute for touchscreens. The default validation message is not useful, so the 'invalid' event should also be handled.

(Just kidding, inputmode isn't supported anywhere. You should use <input type=tel> to show a numeric keyboard on touchscreen devices.)

<form>
  <input name=num type=tel
         required pattern="\d+"
         oninvalid="setCustomValidity('A number is required')"
         oninput="setCustomValidity('')">
  <input type=submit>
</form>

There's a note in the spec about credit card numbers:

The type=number state is not appropriate for input that happens to only consist of numbers but isn't strictly speaking a number. For example, it would be inappropriate for credit card numbers or US postal codes. A simple way of determining whether to use type=number is to consider whether it would make sense for the input control to have a spinbox interface (e.g. with "up" and "down" arrows).

See: https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number)

like image 188
Josh Lee Avatar answered Oct 16 '22 08:10

Josh Lee