You are here

function name_element_validate in Name Field 7

Same name and namespace in other branches
  1. 8 name.module \name_element_validate()
  2. 6 name.module \name_element_validate()

A custom validator to check the components of a name_element element.

1 string reference to 'name_element_validate'
name_element_info in ./name.module
Implements hook_element_info().

File

./name.module, line 753
Defines an API for displaying and inputing names.

Code

function name_element_validate($element, &$form_state) {

  // Limits validation to posted values only.
  if (empty($element['#needs_validation'])) {
    return $element;
  }
  $minimum_components = array_filter($element['#minimum_components']);
  $labels = array();
  foreach ($element['#components'] as $key => $component) {
    if (!isset($component['exclude'])) {
      $labels[$key] = $component['title'];
    }
  }
  $item = $element['#value'];
  $empty = name_field_is_empty($item, NULL);
  $item_components = array();
  foreach (_name_translations() as $key => $title) {
    if (isset($labels[$key]) && !empty($item[$key])) {
      $item_components[$key] = 1;
    }
  }

  // Conditionally allow either a single given or family name.
  if (!empty($element['#allow_family_or_given'])) {

    // This option is only valid if there are both components.
    if (isset($labels['given']) && isset($labels['family'])) {
      if (!empty($item['given']) || !empty($item['family'])) {
        $item_components['given'] = 1;
        $item_components['family'] = 1;
      }
    }
  }
  if (!$empty && count($minimum_components) != count(array_intersect_key($minimum_components, $item_components))) {
    $missing_labels = array_diff_key(array_intersect_key($labels, $minimum_components), $item_components);
    $label = empty($element['#title']) ? empty($element['#label']) ? 'Field' : $element['#label'] : $element['#title'];

    // Note that field_default_form() has already sanitized #title.
    form_error($element[key($missing_labels)], t('!name also requires the following parts: <em>!components</em>.', array(
      '!name' => $label,
      '!components' => implode(', ', $missing_labels),
    )));
  }
  if ($empty && $element['#required']) {
    form_error($element, t('<em>!name</em> is required.', array(
      '!name' => t($element['#title']),
    )));
  }
  return $element;
}