giggsey / libphonenumber-for-php

PHP version of Google's phone number handling library

Home Page:https://giggsey.com/libphonenumber/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Return False instead of Catch exception

mimoudix opened this issue · comments

Hello, I am using "https://intl-tel-input.com/" to handle the client-side number input. Then, I am utilizing your solution to handle it server-side before inserting it into the database. However, it seems that the AJAX request fails due to exceptions being thrown if the user, for instance, enters a string instead of a valid phone number. This leads to an Exception being thrown: libphonenumber\NumberParseException (1), indicating that the supplied string does not appear to be a phone number.

Additionally, if the user attempts to spam the input field, for instance, by entering "+693278379," it triggers a fatal error: Fatal error: Uncaught Error type: 0. Could not interpret numbers after the plus-sign.

here is my function

function isvalidPhoneNumber($phoneNumber)
{


  $phoneNumberUtil = \libphonenumber\PhoneNumberUtil::getInstance();
  $phoneNumberObject = $phoneNumberUtil->parse($phoneNumber, null);

  return $phoneNumberUtil->isValidNumber($phoneNumberObject);
}

The parse() function will throw exceptions if the input is obviously wrong.

To match it into your code, catch the Number Parse Exception and return false.

function isvalidPhoneNumber($phoneNumber)
{
  $phoneNumberUtil = \libphonenumber\PhoneNumberUtil::getInstance();

  try {
    $phoneNumberObject = $phoneNumberUtil->parse($phoneNumber, null);
    return $phoneNumberUtil->isValidNumber($phoneNumberObject);
  } catch (\libphonenumber\NumberParseException $e) {
    return false; // Return false in case of NumberParseException
  }
}
 it worked thanks !!

It would be very beneficial to include this in tutorial

It would be very beneficial to include this in tutorial

The exceptions are mentioned in both the docblocks and documentation and even the quick example.

Regardless, I'm glad you got it working. Closing issue.