An Ecto.ParameterizedType storing a phone number as E.164 text.
A phone number is stored in its E.164 form — "+16502530000" — which
is the one representation that identifies a number unambiguously
worldwide. That makes the column a natural key: it can carry a unique
index, be compared for equality, and be matched by prefix to find
every number in a country, none of which works reliably against a
number stored the way a person happened to type it.
Values load as a Localize.PhoneNumber.Number.t/0, so the loaded
number formats for display in any style:
iex> {:ok, number} = Localize.PhoneNumber.parse("+1 650-253-0000")
iex> Localize.PhoneNumber.to_string(number, :national)
{:ok, "(650) 253-0000"}Schema
The column is ordinary text, so no migration beyond the column itself is needed:
# in a migration
add :phone, :string
create unique_index(:contacts, [:phone])
# in a schema
field :phone, Localize.PhoneNumber.Ecto.TypeCasting national formats
A number typed without an international prefix cannot be resolved
without knowing the country it belongs to. Give the field a
:territory or a :locale and locally formatted input casts
correctly:
field :phone, Localize.PhoneNumber.Ecto.Type, territory: "GB"With no option, the territory comes from Localize.get_locale/0 at
the moment of the cast, as in Localize.PhoneNumber.parse/2.
Options
:territoryis an ISO 3166-1 alpha-2 territory code used as the default territory when casting a number that is not in international format.:localeis a locale identifier from which the default territory is derived.