Skip to content

Commit

Permalink
More precise phone number validation
Browse files Browse the repository at this point in the history
  • Loading branch information
JhumanJ committed Sep 23, 2023
1 parent 3223248 commit ae41af4
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions app/Rules/ValidPhoneInputRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,34 @@

class ValidPhoneInputRule implements Rule
{

public ?int $reason;

public function passes($attribute, $value)
{
if (!is_string($value) || !Str::startsWith($value, '+')) {
return false;
}

try {
$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
return $phoneUtil->isValidNumber($phoneUtil->parse($value));
$phone = $phoneUtil->parse($value);
$this->reason = $phoneUtil->isPossibleNumberWithReason($phone);
return $this->reason === \libphonenumber\ValidationResult::IS_POSSIBLE;
} catch (\Exception $e) {
return false;
}
}

public function message()
{
return 'The :attribute is invalid.';
return match ($this->reason) {
\libphonenumber\ValidationResult::IS_POSSIBLE => 'The :attribute is not valid for an unknown reason.',
\libphonenumber\ValidationResult::INVALID_COUNTRY_CODE => 'The :attribute does not have a valid country code.',
\libphonenumber\ValidationResult::TOO_SHORT => 'The :attribute is too short.',
\libphonenumber\ValidationResult::TOO_LONG => 'The :attribute is too long.',
\libphonenumber\ValidationResult::IS_POSSIBLE_LOCAL_ONLY => 'The :attribute is not a valid phone number (local number).',
\libphonenumber\ValidationResult::INVALID_LENGTH => 'The :attribute does not have a valid length.',
default => 'The :attribute is not a valid phone number.',
};
}
}
}

0 comments on commit ae41af4

Please sign in to comment.