You are here

public static function WebformTime::validateWebformTime in Webform 8.5

Same name and namespace in other branches
  1. 6.x src/Element/WebformTime.php \Drupal\webform\Element\WebformTime::validateWebformTime()

Webform element validation handler for #type 'webform_time'.

Note that #required is validated by _form_valistatic::formatTime() already.

File

src/Element/WebformTime.php, line 100

Class

WebformTime
Provides a webform element for time selection.

Namespace

Drupal\webform\Element

Code

public static function validateWebformTime(&$element, FormStateInterface $form_state, &$complete_form) {
  $has_access = Element::isVisibleElement($element);
  $value = $element['#value'];
  if (trim($value) === '') {
    return;
  }
  $time = strtotime($value);

  // Make the submitted value is parsable and in the specified
  // custom format (ex: g:i A) or default format (ex: H:i).
  //
  // This accounts for time values generated by an HTML5 time input or
  // the jQuery Timepicker.
  //
  // @see \Drupal\webform\Plugin\WebformElement\DateBase::validateDate
  // @see https://github.com/jonthornton/jquery-timepicker
  // @see js/webform.element.time.js
  $is_valid_time = $time && ($value === static::formatTime('H:i', $time) || $value === static::formatTime('H:i:s', $time) || $value === static::formatTime($element['#time_format'], $time));
  if (!$is_valid_time) {
    if ($has_access) {
      if (isset($element['#title'])) {
        $form_state
          ->setError($element, t('%name must be a valid time.', [
          '%name' => $element['#title'],
        ]));
      }
      else {
        $form_state
          ->setError($element);
      }
    }
    return;
  }
  $name = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];
  $time_format = $element['#time_format'];

  // Ensure that the input is greater than the #min property, if set.
  if ($has_access && isset($element['#min'])) {
    $min = strtotime($element['#min']);
    if ($time < $min) {
      $form_state
        ->setError($element, t('%name must be on or after %min.', [
        '%name' => $name,
        '%min' => static::formatTime($time_format, $min),
      ]));
    }
  }

  // Ensure that the input is less than the #max property, if set.
  if ($has_access && isset($element['#max'])) {
    $max = strtotime($element['#max']);
    if ($time > $max) {
      $form_state
        ->setError($element, t('%name must be on or before %max.', [
        '%name' => $name,
        '%max' => static::formatTime($time_format, $max),
      ]));
    }
  }

  // Convert time to 'H:i:s' format.
  $value = static::formatTime('H:i:s', $time);
  $element['#time_format'] = 'H:i:s';
  $element['#value'] = $value;
  $form_state
    ->setValueForElement($element, $value);
}