Validation determines whether a parsed phone number is legitimate according to that country’s numbering plan. Understanding the difference between “possible” and “valid” numbers is crucial.
This library validates number patterns only. It cannot determine if a number is actually in service with a telecommunication provider.
if (!$phoneUtil->isPossibleNumber($number)) { $reason = $phoneUtil->isPossibleNumberWithReason($number); switch ($reason) { case \libphonenumber\ValidationResult::TOO_SHORT: return ['error' => 'Phone number is too short']; case \libphonenumber\ValidationResult::TOO_LONG: return ['error' => 'Phone number is too long']; default: return ['error' => 'Phone number is invalid']; }}
3
Validate the Number
if (!$phoneUtil->isValidNumber($number)) { return ['error' => 'Phone number is not valid for any region'];}
4
Optional: Check Region
// If you need to ensure it's from a specific regionif (!$phoneUtil->isValidNumberForRegion($number, 'GB')) { return ['error' => 'Phone number must be a UK number'];}
5
Success
// Number is valid, format for storage$e164 = $phoneUtil->format( $number, \libphonenumber\PhoneNumberFormat::E164);return ['success' => true, 'number' => $e164];
You can validate that a number is of a specific type:
$phoneUtil = PhoneNumberUtil::getInstance();$number = $phoneUtil->parse('07400 123456', 'GB');// Check if it's a mobile number$type = $phoneUtil->getNumberType($number);if ($type === \libphonenumber\PhoneNumberType::MOBILE) { echo "This is a mobile number";} elseif ($type === \libphonenumber\PhoneNumberType::FIXED_LINE) { echo "This is a landline";}// Validate as possible for specific type$result = $phoneUtil->isPossibleNumberForTypeWithReason( $number, \libphonenumber\PhoneNumberType::MOBILE);
Sometimes you want to accept numbers from several countries:
function isValidForAnyRegion( PhoneNumber $number, array $allowedRegions): bool { $phoneUtil = PhoneNumberUtil::getInstance(); foreach ($allowedRegions as $region) { if ($phoneUtil->isValidNumberForRegion($number, $region)) { return true; } } return false;}// Accept UK or US numbers$isValid = isValidForAnyRegion($number, ['GB', 'US']);
Premium rate number detection
Identify expensive premium rate numbers:
$phoneUtil = PhoneNumberUtil::getInstance();$number = $phoneUtil->parse($input, $region);$type = $phoneUtil->getNumberType($number);if ($type === \libphonenumber\PhoneNumberType::PREMIUM_RATE) { // Show warning to user about potential costs echo "Warning: This is a premium rate number";}