DEV Community

Pablo Cirre
Pablo Cirre

Posted on

Zero-Dependency 249-Country UPU S42 Postal Code Validator & Leading-Zero Guard (JS + Python)

International checkout forms and B2B ETL pipelines break on postal codes far more often than most teams expect.

Three recurring production bugs account for over 80% of shipping and geocoding failures:

  1. Excel & CSV Leading-Zero Truncation: Numeric parsers silently strip the leading 0 from US East Coast ZIP codes (01001–09999), German eastern PLZ (01067–09999), and 9 Spanish provinces (01xxx–09xxx, including Barcelona 08001).
  2. Alphanumeric Space Normalization: UK (SW1A 1AA), Canadian (M5V 3L9), Dutch (1012 JS), and Irish Eircode (D02 X285) formats break naive \d{5} validators.
  3. No-Postal-Code Territories: Over 60 countries and territories (including the UAE, Hong Kong, Panama, and Qatar) do not use national postal codes — forcing a mandatory ZIP field at checkout kills conversion.

UPU S42 Reference Matrix Across Major Markets

Country (ISO-2) Official System Verified Format Strict Regex Leading-Zero Risk
United States (US) ZIP / ZIP+4 10001 or 10001-1234 ^\d{5}(?:-\d{4})?$ High (00501–09999)
Germany (DE) Postleitzahl (PLZ) 10115 ^\d{5}$ High (01067–09999)
Spain (ES) Código Postal 28001 `^(?:0[1-9]\ [1-4]\d\
Netherlands ({% raw %}NL) PC4 / PC6 1012 JS ^[1-9]\d{3}\s?[A-Z]{2}$ None
United Kingdom (GB) Outward + Inward SW1A 1AA ^[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}$ None
Portugal (PT) Código Postal 1000-001 ^\d{4}-\d{3}$ None
Canada (CA) FSA + LDU M5V 3L9 ^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z]\s?\d[ABCEGHJ-NPRSTV-Z]\d$ None
United Arab Emirates (AE) Makani / P.O. Box No national code Checkout fallback (optional) N/A

Preserving Leading Zeros in SQL, Python & JavaScript

Before running regex validation or joining against WGS84 centroids, always store postal codes as VARCHAR(16) and pad numeric countries defensively:

NUMERIC_5_DIGIT = {"US", "DE", "ES", "FR", "IT", "MX", "ID", "FI"}

def normalize_postal_code(country_iso: str, raw_code: str) -> str:
    cc = country_iso.strip().upper()
    code = " ".join(str(raw_code).strip().upper().split())
    if cc in NUMERIC_5_DIGIT and code.isdigit() and len(code) < 5:
        code = code.zfill(5)
    return code
Enter fullscreen mode Exit fullscreen mode
export function validatePostalCode(countryIso, rawCode, rules) {
  const spec = rules[countryIso.toUpperCase()];
  if (!spec) return { valid: false, reason: "unknown_country" };
  if (!spec.has_postal_codes) {
    return { valid: true, optional: true, fallback: spec.checkout_fallback };
  }
  const normalized = String(rawCode || "").trim().toUpperCase();
  const re = new RegExp(spec.regex);
  return { valid: re.test(normalized), normalized, format: spec.format };
}
Enter fullscreen mode Exit fullscreen mode

Open-Source 249-Country UPU S42 Dataset, Validator & OpenAPI 3.1

We packaged all 249 ISO-3166-1 alpha-2 country regexes, checkout fallback rules, and unit tests into an MIT-licensed toolkit (postalcodes-upu-regex) backed by PostalCodes.info Global Postal Datasets:

If you maintain multi-country checkouts or freight-zone tables, normalizing leading zeros and making non-postal territories optional eliminates one of the quietest conversion leaks in international e-commerce.

Top comments (0)