Provides javascript postal code validation for all countries. Supports both Node.js and web browser usage.
- Characters " " (space) and "-" (dash) are removed from the input string.
- Input is case insensitive.
- Supports both ISO 3166-1 alpha-2 and ISO 3166-1 alpha-3 country codes.
- Validates optional n-digit extention seperated by a space or hyphen.
const postalCodes = require('postal-codes-js');
const countryCode = 'CH'; // ISO 3166-1 alpha-2 or alpha-3 country code as string.
const postalCode = '8008'; // Postal code as string or number.
postalCodes.validate(countryCode, postalCode); // Returns 'true' if valid, error message as string otherwise.
// All the calls below returns true
postalCodes.validate('bg', '1003');
postalCodes.validate('gb', 'EC1A 1BB');
postalCodes.validate('GB', 'EC1A 1BB');
postalCodes.validate('GBR', 'EC1A 1BB');
postalCodes.validate('gb', 'EC1A1BB');
postalCodes.validate('gb', 'EC1A-1BB');
postalCodes.validate('tr', '33150');
postalCodes.validate('TR', '33150');
postalCodes.validate('TUR', '33150');
postalCodes.validate('us', '22313');
postalCodes.validate('USA', '91746-2302');
// All the calls below return a string
postalCodes.validate('UK', 'EC1A 1BB');
> Unknown alpha2/alpha3 country code: UK
postalCodes.validate('PL', '9999');
> Postal code 9999 is not valid for country PL
postalCodes.validate('CH');
> Missing postal code.
$ npm test
$ npm run coverage
Contributions are more than welcome, just fork the repo and create a pull-request ;)
cd ~/src/postal-codes
npm install
node build/generate-mappings.js
1. Check if the country is already covered or not under a format in
/mappings/alpha2-to-formats.json
2. Remove that country from the list nested under a format
3. Define a new format for the country - usually its alpha2 name under
/formats
4. Define the country's code removed in step 2 under the new format that
was newly created, for example:
"IL.json": [
"IL"
],
and add it to the list in alphabetical order.
5. Run node build/generate-mappings.js