htmlhtml-input

Can I pad number with zeros in HTML <input type="number" />?


I have input for entering hours. To make it clear for the user that the number is an hour, I want to pad single digit hours with leading zero, e.g. show "02" instead of "2". Is that possible with HTML <input type="number" />? When I give it value="02" it renders 2 instead of 02. So far the only solution I found is using <input type="text" /> instead.


Solution

  • According to the HTML5 definitions there is no option for specifying a format for the number. Nowadays latest browsers do not treat the number input the same anyway (see "Known issues" at https://caniuse.com/#feat=input-number).

    I fear the only option to force a given pattern in the input involves JavaScript.

    Sources: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number, https://www.w3.org/TR/html5/sec-forms.html#number-state-typenumber, https://www.w3.org/TR/html5/infrastructure.html#valid-floating-point-number