You are here

public static function DateBase::validateDate in YAML Form 8

Form element validation handler for base elements.

Note that #required is validated by _form_validate() already.

See also

\Drupal\Core\Render\Element\Number::validateNumber

File

src/Plugin/YamlFormElement/DateBase.php, line 245

Class

DateBase
Provides a base 'date' class.

Namespace

Drupal\yamlform\Plugin\YamlFormElement

Code

public static function validateDate(&$element, FormStateInterface $form_state, &$complete_form) {
  $value = $element['#value'];

  // Convert DrupalDateTime array and object to ISO datetime.
  if (is_array($value)) {

    /** @var \Drupal\Core\Datetime\DrupalDateTime $datetime */
    if ($datetime = $value['object']) {
      $value = $datetime
        ->format('c');
    }
    else {
      $value = '';
    }
    $form_state
      ->setValueForElement($element, $value);
  }
  if ($value === '') {
    return;
  }
  $name = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];

  // Ensure the input is valid date.
  // @see http://stackoverflow.com/questions/10691949/check-if-variable-is-a-valid-date-with-php
  $date = date_parse($value);
  if ($date["error_count"] || !checkdate($date["month"], $date["day"], $date["year"])) {
    $form_state
      ->setError($element, t('%name must be a valid date.', [
      '%name' => $name,
    ]));
  }
  $time = strtotime($value);
  $date_date_format = !empty($element['#date_date_format']) ? $element['#date_date_format'] : DateFormat::load('html_date')
    ->getPattern();

  // Ensure that the input is greater than the #min property, if set.
  if (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' => date($date_date_format, $min),
      ]));
    }
  }

  // Ensure that the input is less than the #max property, if set.
  if (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' => date($date_date_format, $max),
      ]));
    }
  }
}