Created
April 24, 2012 12:44
-
-
Save jeremy2/2479338 to your computer and use it in GitHub Desktop.
HTML input fields used for Zip Codes should be type=text and use the pattern attribute to provide hints to the browser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- | |
- | |
- US Zip Codes are text (not numbers) made up of digits (and optionally the dash character, if you accept 9 digit codes) | |
- | |
- Number input fields will drop leading zeros and may add numeric formatting (ie- add commas) to the input. This behavior | |
- is incorrect for Zip Codes which can have leading zeros and should not include commas. | |
- | |
- This Gist shows the incorrect and correct way to tell the browser what is expected in a Zip Code field. Oddly, HTML5 | |
- adds 'date', 'time' and 'tel' types to input elements, but does not include 'zip'. | |
- | |
- This hint not only allows the browser to flag invalid input, it also allows Mobile Safari to present a different | |
- keyboard to the user. On the iPhone, the user will be provided the numeric keypad for this field, instead of a full | |
- text keyboard. | |
- | |
--> | |
<form> | |
<input id="the_wrong_way" class="zipcode" type="number" value=""> | |
<input id="the_right_way" class="zipcode" type="text" value = "" pattern="\d*"> | |
</form> |
hey
Or event simpler… \d{5}-?(\d{4})?
(test on regexr.com)
- removed the second 5 and 4, because there must be 5 digits or 9 digits.
- the dash is also optional.
can any one tell how to give range of postal code 20000-40000 postal code should be in this range need simple html code
@beausmith FWIW that pattern doesn't trigger a numeric keyboard on iOS.
For anyone looking, this post covers this topic in depth: https://www.filamentgroup.com/lab/type-number.html
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Actually, full US ZIP codes are in the format of 5-4. The -4 is not mandatory