Skip to content

phone, detectCountry, phoneCountries ​

A single-country mask, country detection by number and the list of all countries — with the same API as in tinyval-mask/presets.

Signature ​

ts
function phone(country: PhoneCountry): Mask
function detectCountry(number: string, countries?: PhoneCountry[]): PhoneCountry | undefined
function phoneCountries(): CountryInfo[]
const phoneTable: Record<PhoneCountry, [dial, pattern, trunk?, detect?]> // данные пакета
function setCountries(countries: Record<string, CountryEntry | null>, options?: { replace?: boolean }): void
function getCountries(): PhoneTable // с изменениями из setCountries

// из tinyval-mask/presets, для удобства
function flag(code: string): string
function countryName(code: string, locale?: string): string

Notes ​

  • phone(country) — a mask with the country code at the start: +81 99-9999-9999. The code doesn't have to be typed, nor does the national prefix: 09012345678 → +81 90-1234-5678.
  • detectCountry looks at digits including the country code and doesn't know about a default country: detectCountry('9012345678') is +90 (Turkey).
  • phoneCountries() — 245 countries in alphabetical order of codes. Names come from countryName in the UI language.
  • setCountries changes, adds (ab: […]) and removes (xk: null) countries for all functions of the package; replace: true — only the given ones. Call it once on startup, before creating masks. A file to edit — npx tinyval-phone countries, see Your own countries & flags.

Examples ​

ts
import { mask } from 'tinyval-mask';
import { phone, detectCountry, phoneCountries, countryName } from 'tinyval-phone';

mask('09012345678', phone('jp'));   // '+81 90-1234-5678'
mask('0612345678', phone('fr'));    // '+33 6 12 34 56 78'
detectCountry('+971501234567');     // 'ae'
detectCountry('+1 242 359 1234');   // 'bs'

// свой выбор страны
const options = phoneCountries().map((c) => ({
  value: c.code,
  label: `${c.flag} ${countryName(c.code, 'ru')} +${c.dial}`,
}));

See also ​