You are here

function name_element_validate in Name Field 8

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

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

1 string reference to 'name_element_validate'
Name::getInfo in src/Element/Name.php
Returns the element properties for this element.

File

./name.module, line 546
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 = [];
  foreach ($element['#components'] as $key => $component) {
    if (!isset($component['exclude'])) {
      $labels[$key] = $component['title'];
    }
  }
  $item = $element['#value'];
  $empty = name_element_validate_is_empty($item);
  $item_components = [];
  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_components = array_diff(array_keys($minimum_components), array_keys($item_components));
    $missing_components = array_combine($missing_components, $missing_components);
    $missing_labels = array_intersect_key($labels, $missing_components);

    // Generate error message for the first missing element.
    $form_state
      ->setError($element[key($missing_labels)], t('@name also requires the following parts: <em>@components</em>.', [
      '@name' => $element['#title'],
      '@components' => implode(', ', $missing_labels),
    ]));

    // Mark the other missing elements too, but hide the error message.
    foreach ($missing_labels as $key => $label) {
      $form_state
        ->setError($element[$key]);
    }
  }
  if ($empty && $element['#required']) {
    $form_state
      ->setError($element, t('@name field is required.', [
      '@name' => $element['#title'],
    ]));
  }
  return $element;
}