Evan
Evan

Reputation: 835

HTML5 Input type=number removes leading zero

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). Is there an attribute to force the zero to remain in the field after it loses focus? The application for this is numeric data such as international phone prefixes.

Upvotes: 50

Views: 92564

Answers (5)

Just Shadow
Just Shadow

Reputation: 11941

8 Years later...

Beware:
The answers with the usage of type="tel" don't fully solve the issue especially in the 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 a numeric field (with all the other allowed characters).
And the inputmode="numeric" will pull the numeric keyboard instead of the default one.

Upvotes: 16

Guillaume Gendre
Guillaume Gendre

Reputation: 2534

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

Upvotes: 23

Lar
Lar

Reputation: 591

<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.

Upvotes: 59

Evan
Evan

Reputation: 835

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).

Upvotes: 5

Dennis Traub
Dennis Traub

Reputation: 51694

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

Upvotes: 42

Related Questions