You are here

public static function TextBase::validateCounter in Webform 8.5

Same name and namespace in other branches
  1. 6.x src/Plugin/WebformElement/TextBase.php \Drupal\webform\Plugin\WebformElement\TextBase::validateCounter()

Form API callback. Validate (word/character) counter.

File

src/Plugin/WebformElement/TextBase.php, line 212

Class

TextBase
Provides a base 'text' (field) class.

Namespace

Drupal\webform\Plugin\WebformElement

Code

public static function validateCounter(array &$element, FormStateInterface $form_state) {
  $value = $element['#value'];
  if ($value === '') {
    return;
  }
  $type = $element['#counter_type'];
  $max = !empty($element['#counter_maximum']) ? $element['#counter_maximum'] : NULL;
  $min = !empty($element['#counter_minimum']) ? $element['#counter_minimum'] : NULL;

  // Display error.
  // @see \Drupal\Core\Form\FormValidator::performRequiredValidation
  $t_args = [
    '@type' => $type === 'character' ? t('characters') : t('words'),
    '@name' => $element['#title'],
    '%max' => $max,
    '%min' => $min,
  ];

  // Get character/word count.
  if ($type === 'character') {
    $length = mb_strlen($value);
    $t_args['%length'] = $length;
  }
  elseif ($type === 'word') {
    $length = WebformTextHelper::wordCount($value);
    $t_args['%length'] = $length;
  }

  // Validate character/word count.
  if ($max && $length > $max) {
    $form_state
      ->setError($element, t('@name cannot be longer than %max @type but is currently %length @type long.', $t_args));
  }
  elseif ($min && $length < $min) {
    $form_state
      ->setError($element, t('@name must be longer than %min @type but is currently %length @type long.', $t_args));
  }
}