Skip to content

Commit

Permalink
Do not validate phone numbers from other regions
Browse files Browse the repository at this point in the history
I'm unsure whether this is a bug in "libphonenumber-for-php" or if we're
misusing the library. This commit will ensure that only phone numbers
from a specific region will be considered valid. I've reported the issue
to "libphonenumber-for-php" anyways [1].

[1]: giggsey/libphonenumber-for-php#621

Signed-off-by: Henrique Moody <[email protected]>
  • Loading branch information
henriquemoody committed Mar 24, 2024
1 parent ccec34c commit 263ae11
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
15 changes: 11 additions & 4 deletions library/Rules/Phone.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,20 @@ public function validate($input): bool
return preg_match($this->getPregFormat(), (string) $input) > 0;
}

return $this->isValidRegionalPhoneNumber((string) $input, $this->countryCode);
}

private function isValidRegionalPhoneNumber(string $input, string $countryCode): bool
{
try {
return PhoneNumberUtil::getInstance()->isValidNumber(
PhoneNumberUtil::getInstance()->parse((string) $input, $this->countryCode)
);
$phoneNumberUtil = PhoneNumberUtil::getInstance();
$phoneNumberObject = $phoneNumberUtil->parse($input, $countryCode);

return $phoneNumberUtil->getRegionCodeForNumber($phoneNumberObject) === $countryCode;
} catch (NumberParseException) {
return false;
}

return false;
}

private function getPregFormat(): string
Expand Down
1 change: 1 addition & 0 deletions tests/unit/Rules/PhoneTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ public static function providerForInvalidInput(): array
[new Phone(), []],
[new Phone(), '+1-650-253-00-0'],
[new Phone('BR'), '+1 11 91111 1111'], // invalid + code for BR
[new Phone('BR'), '+1 650 253 00 00'], // invalid + code for BR
];
}
}

0 comments on commit 263ae11

Please sign in to comment.