isValidNumberForRegion method

bool isValidNumberForRegion(
  1. PhoneNumber number,
  2. String? regionCode
)

Tests whether a phone number is valid for a certain region. Note this doesn't verify the number is actually in use, which is impossible to tell by just looking at a number itself. If the country calling code is not the same as the country calling code for the region, this immediately exits with false. After this, the specific number pattern rules for the region are examined. This is useful for determining for example whether a particular number is valid for Canada, rather than just a valid NANPA number. Warning: In most cases, you want to use {@link #isValidNumber} instead. For example, this method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for the region 'GB' (United Kingdom), since it has its own region code, 'IM', which may be undesirable.

number the phone number that we want to validate. regionCode the region that we want to validate the phone number for. isValidNumberForRegion returns a boolean that indicates whether the number is of a valid pattern.

Implementation

bool isValidNumberForRegion(PhoneNumber number, String? regionCode) {
  int countryCode = number.countryCode;
  PhoneMetadata? metadata =
      _getMetadataForRegionOrCallingCode(countryCode, regionCode);
  if (metadata == null ||
      (regionCodeForNonGeoEntity != regionCode &&
          countryCode != _getCountryCodeForValidRegion(regionCode))) {
    // Either the region code was invalid, or the country calling code for this
    // number does not match that of the region code.
    return false;
  }
  String nationalSignificantNumber = getNationalSignificantNumber(number);
  return _getNumberTypeHelper(nationalSignificantNumber, metadata) !=
      PhoneNumberType.unknown;
}