You are here

function maxlength_validate_input in Maxlength 7.3

Custom validation handler for the maxlength of input fields that have the maxlength attribute.

1 string reference to 'maxlength_validate_input'
maxlength_process_element in ./maxlength.module
Process handler for the form elements that can have maxlength attribute.

File

./maxlength.module, line 233
Limit the number of characters in textfields and textareas and shows the amount of characters left.

Code

function maxlength_validate_input(&$element, &$form_state) {

  // Verify that the value is not longer than #maxlength characters.
  if (isset($element['#attributes']['maxlength']) && isset($element['#value'])) {

    // Compute the length of the text, without counting the tags, and consider
    // the "enter" characters as only one character.
    $value = filter_xss(str_replace(array(
      "\r\n",
      ' ',
    ), array(
      ' ',
      ' ',
    ), $element['#value']), array());
    $value = strip_tags($value);
    $value = preg_replace("/&#?[a-z0-9]+;/i", "1", $value);
    if (drupal_strlen($value) > $element['#attributes']['maxlength']) {
      form_error($element, t('!name cannot be longer than %max characters but is currently %length characters long.', array(
        '!name' => empty($element['#title']) ? $element['#parents'][0] : $element['#title'],
        '%max' => $element['#attributes']['maxlength'],
        '%length' => drupal_strlen($value),
      )));
    }

    // Giving the element back the #maxlength, maybe some other modules requires it.
    $element['#maxlength'] = $element['#attributes']['maxlength'];
  }
}