1 token.inc token_element_validate(&$element, &$form_state)

Validate a form element that should have tokens in it.

Form elements that want to add this validation should have the #token_types parameter defined.

For example:

$form['my_node_text_element'] = array(
  '#type' => 'textfield',
  '#title' => t('Some text to token-ize that has a node context.'),
  '#default_value' => 'The title of this node is [node:title].',
  '#element_validate' => array('token_element_validate'),
  '#token_types' => array('node'),
  '#min_tokens' => 1,
  '#max_tokens' => 10,
);

File

core/includes/token.inc, line 677
Backdrop placeholder/token replacement system.

Code

function token_element_validate(&$element, &$form_state) {
  $value = isset($element['#value']) ? $element['#value'] : $element['#default_value'];

  if (!backdrop_strlen($value)) {
    // Empty value needs no further validation since the element should depend
    // on using the '#required' FAPI property.
    return $element;
  }

  $tokens = token_scan($value);
  $title = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];

  // Validate if an element must have a minimum number of tokens.
  if (isset($element['#min_tokens']) && count($tokens) < $element['#min_tokens']) {
    $error = format_plural($element['#min_tokens'], 'The !element-title cannot contain fewer than one token.', 'The !element-title must contain at least @count tokens.', array('!element-title' => $title));
    form_error($element, $error);
  }

  // Validate if an element must have a maximum number of tokens.
  if (isset($element['#max_tokens']) && count($tokens) > $element['#max_tokens']) {
    $error = format_plural($element['#max_tokens'], 'The !element-title may not contain more than one token.', 'The !element-title may not contain more than @count tokens.', array('!element-title' => $title));
    form_error($element, $error);
  }

  // Check if the field defines specific token types.
  if (isset($element['#token_types'])) {
    $invalid_tokens = token_get_invalid_tokens_by_context($tokens, $element['#token_types']);
    if ($invalid_tokens) {
      form_error($element, t('The !element-title is using the following invalid tokens: @invalid-tokens.', array('!element-title' => $title, '@invalid-tokens' => implode(', ', $invalid_tokens))));
    }
  }

  return $element;
}