You are here

public static function TextFieldCounterWidgetTrait::validateFieldFormElement in Textfield Counter 8

Validates the field for the maximum number of characters.

Parameters

array $element: The render array for the element to which fiels are being attached.

\Drupal\Core\Form\FormStateInterface $form_state: The Drupal form state.

int $maxlength: The maximum allowed text length against which the field should be validated.

File

src/Plugin/Field/FieldWidget/TextFieldCounterWidgetTrait.php, line 348

Class

TextFieldCounterWidgetTrait
Textfield counter trait. Adds textfield counting functionality.

Namespace

Drupal\textfield_counter\Plugin\Field\FieldWidget

Code

public static function validateFieldFormElement(array $element, FormStateInterface $form_state, $maxlength) {
  $input_exists = FALSE;
  $value = NestedArray::getValue($form_state
    ->getValues(), $element['#parents'], $input_exists);
  $value = is_array($value) ? $value['value'] : $value;
  $value_length = self::getLengthOfSubmittedValue($element, $value);
  if ($value_length > $element['#textfield-maxlength']) {
    $form_state
      ->setError($element, t('@name cannot be longer than %max characters but is currently %length characters long.', [
      '@name' => $element['#title'],
      '%max' => $element['#textfield-maxlength'],
      '%length' => $value_length,
    ]));
  }
}