HTML5 Input type=number removes leading zero

前端 未结 5 833
予麋鹿
予麋鹿 2020-12-02 20:05

In Chrome 15, when using the element as a text field, leading zeros (e.g. 011) are removed even if the number entered does not break the validation rules (e.g. min, max).

相关标签:
5条回答
  • 2020-12-02 20:37

    8 Years later...

    Beware:
    The answers with usage of type="tel" don't fully solve the issue especially in case of numeric fields where you might want to write floating/decimal numbers and other allowed characters (like +-.,).

    Solution:
    Consider using text input with pattern and inputmode like this:

    <input type="text" inputmode="numeric" pattern="[-+]?[0-9]*[.,]?[0-9]+">
    

    Details:
    The pattern there will help to keep leading 0s, and behave like numeric field (with all the other allowed characters).
    And the inputmode="numeric" will pull numeric keyboard instead of the default one.

    0 讨论(0)
  • 2020-12-02 20:50

    <input type="text" pattern="[0-9]*" ...

    that should do it for you. Will bring up the numeric keypad on iPhone and the nicer Android phones I've tested on.

    0 讨论(0)
  • <input type="tel"> has been introduced for this exact purpose. It's one of the new input types in HTML5.

    0 讨论(0)
  • 2020-12-02 20:55

    I needed it for mobiles browsers and I used a mix of both solutions like this :

    <input type="tel" pattern="[0-9]*">
    

    On iOS, the numeric keyboard appear with only numbers available (no # or * symbols) whereas on Android phones, the "tel" is correctly interpreted but not the pattern (not yet on the few phones I have).

    I guess that when android browsers will start to implement "pattern" attribute, this should work fine on android too (as the whatwg spec suggests).

    Until then you will have to check for non numeric characters in your input and remove them. javascript replace(/[^0-9*]/g,'') is useful for this.

    hope this helps

    0 讨论(0)
  • 2020-12-02 20:55

    The answer WHATWG provided me in IRC was that for non-numeric (e.g. not float/int) data that is numeric in nature, text is generally the correct type of input to use. The expection is if you are using something where a specific input type (e.g. telephone numbers, dates) already exists.

    input type=number should only be used for inputs that are literally numbers (int), and not data that uses numerals (such as postal codes).

    0 讨论(0)
提交回复
热议问题