Zip code is the postal code used by the United States Postal Service (USPS). The basic format consists of 5 digits. Later, an extended code was introduced that contains a hyphen and 4 more digits.
Some valid Zip Codes:
- 20521-9000
- 42223
- 85254
Here is a simple function to validate a ZIP code:
function isUSAZipCode(str)
{
return /^\d{5}(-\d{4})?$/.test(str);
}
This function uses a regular expression that checks for 5 digits ( \d{5}
) followed by optional hyphen and four digits( (-\d{4})?
).
Note that this function does not check for the existence of a zip code. It checks only the format.
Here is a working sample of this function. You can try by entering some zip codes in the input box
See the Pen USA Zip code validation
Checking zip code in a list
Suppose a certain service is limited to an area in USA territories. You can check the ZIP code to confirm whether the service is available for a given area.
Here is some sample code to check zip code in a list of available zones
function checkIfAvailable(zip)
{
let zones = ["46001","46002","46003","46102","46202"]
return( zones.indexOf(zip) >= 0 )
}
The code uses the indexOf
function of Javascript Array
to
search for the zip code string in the available zip codes list.
Also, note that the zipcodes saved as strings rather than numbers. This is because the zip code is an identification rather than arithmetic quantity. So 00123
may be a valid zip code. In an arithmetic comparison, it will be equal to 123. (00123 == 123
)
Here is a working prototype:
See the Pen Check Zip code in a list