You are here

function value_is_username in Value is 7

Checks for valid (and optionally existing) user name.

File

./value_is.module, line 173
All the element validators for #element_validate.

Code

function value_is_username($element, &$form_state, $form) {
  $value = $element['#value'];
  if ('' != $value) {
    $must_exist = !empty($element['#exists']);
    if ($must_exist) {
      $field = isset($element['#field']) ? $element['#field'] : 'name';
      $query = db_select('users', 'u');
      $query
        ->addExpression('COUNT(1)', 'num');
      $query
        ->condition($field, $value);
      $exists = (int) $query
        ->execute()
        ->fetchField();
      if (!$exists) {
        $params = array(
          '%title' => $element['#title'],
        );
        $message = t('%title must contain an existing user name.', $params);
        return form_error($element, $message);
      }
    }
    else {
      $error = user_validate_name($value);
      if ($error) {
        return form_error($element, $error);
      }
    }
  }
}