You are here

function phone_element_validate in Phone 7.2

An #element_validate callback for the phone element.

1 string reference to 'phone_element_validate'
_phone_element_info in includes/phone.element.inc
Implements hook_element_info().

File

includes/phone.element.inc, line 183
Provides FAPI implementation for a phone element.

Code

function phone_element_validate(&$element, &$form_state) {

  // Load up libphonenumber.
  phone_libphonenumber();
  $item = $element['#value'];
  if (isset($item['number'])) {
    $phone_input = trim($item['number']);
  }
  if (isset($item['countrycode'])) {
    $countrycode = trim($item['countrycode']);
  }
  $ext_input = '';
  $settings = $element['#phone_settings'];
  if ($settings['enable_extension'] && isset($item['extension'])) {
    $ext_input = trim($item['extension']);
  }
  $error = FALSE;
  if (isset($phone_input) && !empty($phone_input)) {
    $all_countries = $settings['country_options']['all_country_codes'];
    $selection = array_filter($settings['country_options']['country_codes']['country_selection']);
    $valid = phone_libphonenumber_valid($phone_input, $countrycode, $ext_input, $all_countries, $selection);
    if (TRUE !== $valid) {
      $error = $valid;
    }
  }
  elseif ($element['#required']) {
    $error = t('Number is required.');
  }

  // If this is used in a field widget, bubble the errors to be handled
  // by hook_field_validate(). We can set a more useful message there
  // as we'll have full access to the field information, and won't have
  // to write complex code here to handle the case when this is used
  // as it's own FAPI element outside of the field system.
  if (!empty($error)) {
    if (isset($settings['bubble_errors']) && $settings['bubble_errors'] === TRUE) {
      $dummy_element = array(
        '#parents' => array_merge($element['#parents'], array(
          'error',
        )),
      );
      form_set_value($dummy_element, $error, $form_state);
    }
    else {
      form_error($element, t('%name: !error', array(
        '%name' => $element['#title'],
        '!error' => $error,
      )));
    }
  }
}