analyzeNumber function

NumberInfo? analyzeNumber(
  1. String phone
)

Identifies and formats any Pakistani telephone number: mobile, landline, UAN (111), toll-free (0800), premium-rate (0900) or personal (0122).

analyzeNumber('021-111-825-888');
// type: uan, formatted: 021-111-825-888, e164: +9221111825888,
// areaCode: 021, cities: [Karachi]

Returns null if it is not a valid Pakistani number.

Implementation

NumberInfo? analyzeNumber(String phone) {
  final mobile = normalizePhoneDigits(phone);
  if (mobile != null) {
    final national = mobile.substring(2);
    return NumberInfo(
      type: NumberType.mobile,
      formatted: '0${national.substring(0, 3)}-${national.substring(3)}',
      e164: '+$mobile',
    );
  }

  final bareUan =
      _uanWithoutAreaCode.firstMatch(stripSeparators(toAsciiDigits(phone)));
  if (bareUan != null) {
    return NumberInfo(
      type: NumberType.uan,
      formatted: '111-${_groupDigits(bareUan[1]!)}',
      e164: null,
    );
  }

  final national = _toNationalNumber(phone);
  if (national == null) return null;

  NumberInfo service(NumberType type, String prefix, String rest) =>
      NumberInfo(type: type, formatted: '0$prefix-$rest', e164: '+92$national');

  final tollFree = _tollFree.firstMatch(national);
  if (tollFree != null) {
    return service(NumberType.tollFree, '800', tollFree[1]!);
  }
  final premium = _premium.firstMatch(national);
  if (premium != null) return service(NumberType.premium, '900', premium[1]!);
  final personal = _personal.firstMatch(national);
  if (personal != null) {
    return service(NumberType.personal, '122', personal[1]!);
  }

  final uan = _uan.firstMatch(national);
  if (uan != null) {
    final code = uan[1]!;
    return NumberInfo(
      type: NumberType.uan,
      formatted: '0$code-111-${_groupDigits(uan[2]!)}',
      e164: '+92$national',
      areaCode: '0$code',
      cities: _areaCodeMap[code] ?? const [],
    );
  }

  if (_fixedLine.hasMatch(national)) {
    final code = _findAreaCode(national);
    return NumberInfo(
      type: NumberType.landline,
      formatted: code != null
          ? '0$code-${national.substring(code.length)}'
          : '0$national',
      e164: '+92$national',
      areaCode: code != null ? '0$code' : null,
      cities: code != null ? (_areaCodeMap[code] ?? const []) : const [],
    );
  }

  return null;
}