Skip to content

Instantly share code, notes, and snippets.

@jeremy2
Created April 24, 2012 12:44
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremy2/2479338 to your computer and use it in GitHub Desktop.
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
<!--
-
- 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>
@JordanReiter
Copy link

Zip codes can have dashes in them, and US zip codes are always five digits long. So a better pattern would be \d{5,5}(-\d{4,4})?.

@abda53
Copy link

abda53 commented Feb 24, 2015

Actually, full US ZIP codes are in the format of 5-4. The -4 is not mandatory

@abdullahbensaad
Copy link

hey

@beausmith
Copy link

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.

@ashozee
Copy link

ashozee commented Jul 15, 2017

can any one tell how to give range of postal code 20000-40000 postal code should be in this range need simple html code

@paulirish
Copy link

@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