AddressInput (AddressInput v0.3.0)

Copy Markdown View Source

High-level API for address metadata derived from the libaddressinput dataset.

The module loads a JSON dataset from priv/metadata.json (bundled with the application) and exposes convenience functions for looking up normalized Country and Subregion structs.

Primary entry points

  • countries/0 returns all available countries sorted by name. Each country includes parsed subregions.
  • get_country/1 returns a single country by ISO 3166-1 alpha-2 code (case insensitive), or nil if it is not present.

Country fields

A Country includes:

  • id - ISO 3166-1 alpha-2 code.
  • name - localized display name from the dataset.
  • default_language - language code used for labels.
  • required_fields - list of required address components as atoms, derived from the dataset codes (N, O, A, D, C, S, Z, X).
  • subregion_type, sublocality_type, postal_code_type - label hints.
  • postal_code_regex - compiled regex for validating postal codes.
  • address_format - parsed formatting template from the dataset (fmt).
  • local_address_format - parsed local formatting template (lfmt) when present.
  • subregions - list of Subregion entries.

A Subregion includes id, iso_code, and name.

Example

iex> AddressInput.get_country("US")
%AddressInput.Country{
  id: "US",
  name: "UNITED STATES",
  default_language: "en",
  required_fields: [:address, :sublocality, :region, :postal_code],
  sublocality_type: "city",
  subregion_type: "state",
  postal_code_type: "zip",
  postal_code_regex: ~r/(\d{5})(?:[ -](\d{4}))?/,
  address_format: [{:field, :name}, :newline, ...],
  local_address_format: nil,
  subregions: [
    %AddressInput.Subregion{id: "AK", iso_code: "AK", name: "Alaska"},
    ...
  ]
}
"US"

Summary

Functions

Returns the list of available countries as Country structs.

Returns a Country by ISO 3166-1 alpha-2 country code.

Returns {:ok, postal_code} if the postal code matches the expected format for the given country. Otherwise, returns :error. The provided country must be either a %Country{} or a string that resolves to one.

Types

address_format()

@type address_format() :: [token()]

token()

@type token() ::
  {:field, AddressInput.Country.field()} | {:text, String.t()} | :newline

Functions

countries()

@spec countries() :: [AddressInput.Country.t()]

Returns the list of available countries as Country structs.

get_country(country)

@spec get_country(String.t()) :: AddressInput.Country.t() | nil

Returns a Country by ISO 3166-1 alpha-2 country code.

Returns nil when the country is not found.

parse_postal_code(postal_code, country)

@spec parse_postal_code(String.t(), String.t() | AddressInput.Country.t()) ::
  {:ok, String.t()} | :error

Returns {:ok, postal_code} if the postal code matches the expected format for the given country. Otherwise, returns :error. The provided country must be either a %Country{} or a string that resolves to one.