You are here

function _telephone_validation in Telephone Validation 7

Validation callback.

Parameters

string $value: Raw field value.

array $settings: Array of field settings.

Return value

\libphonenumber\PhoneNumber Returns phone number object if number is valid.

Throws

\Exception Throws exception if number is invalid.

2 calls to _telephone_validation()
telephone_validation_element in ./telephone_validation.module
Telephone element validation.
_telephone_validation_metadata_field_property_validation in ./telephone_validation.module
Validation callback wrapper to set only valid data values.

File

./telephone_validation.module, line 281
Validate phone number.

Code

function _telephone_validation($value, $settings = array()) {

  // Be sure we have default settings if user didn't submit field settings
  // form yet.
  $settings += _telephone_validation_get_default_settings();

  // If number looks more or less ok, use google libphonenumber library to
  // parse  it.
  $phone_util = \libphonenumber\PhoneNumberUtil::getInstance();

  // If number will be incorrect (there will be no way to parse it) we will
  // get an exception here.
  $default_region = $settings['valid_format'] == \libphonenumber\PhoneNumberFormat::NATIONAL ? $settings['valid_countries'] : NULL;
  $number = $phone_util
    ->parse($value, $default_region);

  // If can be parsed do validation.
  if (!$phone_util
    ->isValidNumber($number)) {
    throw new Exception('Field value is invalid.');
  }

  // If valid_countries element is not empty and default region can be loaded
  // do region matching validation.
  // This condition is always TRUE for national phone number format.
  if (!empty($settings['valid_countries']) && ($default_region = $phone_util
    ->getRegionCodeForNumber($number))) {

    // If number should belong to one of selected countries.
    // This condition is always TRUE for national phone number format.
    if (!isset($settings['valid_countries'][$default_region]) && $settings['valid_countries'] != $default_region) {
      throw new Exception('Field does not support phone number from your country.');
    }
  }
  return $number;
}