Skip to content

phone, detectCountry, phoneCountries ​

Маска одной страны, определение страны по номеру и список всех стран — с тем же API, что в tinyval-mask/presets.

Сигнатура ​

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

Особенности ​

  • phone(country) — маска с кодом страны в начале: +81 99-9999-9999. Код можно не набирать, национальную приставку — тоже: 09012345678 → +81 90-1234-5678.
  • detectCountry ищет по цифрам с кодом страны и не учитывает страну по умолчанию: detectCountry('9012345678') — это +90 (Турция).
  • phoneCountries() — 245 стран в алфавитном порядке кодов. Названия — через countryName на языке интерфейса.
  • setCountries меняет, добавляет (ab: […]) и убирает (xk: null) страны для всех функций пакета; replace: true — только переданные. Вызывайте один раз при старте, до создания масок. Файл для правки — npx tinyval-phone countries, см. Свои страны и флаги.

Примеры ​

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}`,
}));

См. также ​