You are here

public static function TextBase::validateCounter in YAML Form 8

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

File

src/Plugin/YamlFormElement/TextBase.php, line 147

Class

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

Namespace

Drupal\yamlform\Plugin\YamlFormElement

Code

public static function validateCounter(array &$element, FormStateInterface $form_state) {
  $name = $element['#name'];
  $value = $form_state
    ->getValue($name);
  $type = $element['#counter_type'];
  $limit = $element['#counter_maximum'];

  // Validate character count.
  if ($type == 'character' && Unicode::strlen($value) <= $limit) {
    return;
  }
  elseif ($type == 'word' && str_word_count($value) <= $limit) {
    return;
  }

  // Display error.
  $t_args = [
    '%name' => $name,
    '@limit' => $limit,
    '@type' => $type == 'character' ? t('characters') : t('words'),
  ];
  $form_state
    ->setError($element, t('%name must be less than @limit @type.', $t_args));
}