TIL I have been using number inputs wrongly and I've seen many others do the same.
HTML number input is not for any type of number value, it is designed to be used only for numbers that are incremental and is not appropriate for non-incremental values even if they are made up of numbers.
So this means it can be used to capture an amount of something such as number of products to buy.
<!-- β
Correct --->
<label for="products">Number of products to buy: </label>
<input id="products" type="number" name="products" value="0" />
But it cannot be used for phone numbers, postal codes and credit card numbers, because these are not incremental numbers.
<!-- β Wrong --->
<label for="phone_no">Phone number:</label>
<input id="phone_no" type="number" name="phone_no" value="0" />
This also explains why it has a stepper button (in most browsers), which doesn't make much sense for phone numbers or credit card numbers.
According to the MDN Web Docs:
The number input type should only be used for incremental numbers, especially when spinbutton incrementing and decrementing are helpful to user experience. The number input type is not appropriate for values that happen to only consist of numbers but aren't strictly speaking a number, such as postal codes in many countries or credit card numbers.
To capture postal codes (and other non-incremental values) use <input>
with inputmode
attribute.
<!-- β
Correct --->
<label for="postal_code">Postal Code:</label>
<input id="postal_code" type="text" inputmode="numeric" pattern="\d*" />
For phone numbers <input type="tel">
can also be used.
<!-- β
Correct --->
<label for="phone_no">Phone number:</label>
<input type="tel" id="phone_no" name="phone_no" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" />
Read more on MDN:
Top comments (0)