Skip to content

Instantly share code, notes, and snippets.

@mmccollow
Created February 25, 2010 20:04
Show Gist options
  • Save mmccollow/314971 to your computer and use it in GitHub Desktop.
Save mmccollow/314971 to your computer and use it in GitHub Desktop.
name = Suggest Login
description = Suggests an account to login with that has a similar name to an invalid attempt.
core="6.x"
version="6.x-1.0"
<?php
/**
* Implementation of hook_form_alter
**/
function suggest_login_form_alter(&$form, $form_state, $form_id) {
if($form['#id'] === 'user-login-form') {
$form['#validate'][0] = 'suggest_login_validate';
}
}
function suggest_login_validate(&$form, $form_state) {
user_login_name_validate($form, $form_state);
$res = db_query("SELECT name FROM {users}");
while($row = db_fetch_array($res)) {
if(strlen($row['name']) > 0) {
$accounts[] = $row['name'];
}
}
$input = $form_state['values']['name'];
if(!in_array($input, $accounts)) {
$shortest = -1;
foreach($accounts as $account) {
$lev = levenshtein($input, $account);
if($lev == 0) {
$closest = $account;
$shortest = 0;
break;
}
if($lev <= $shortest || $shortest < 0) {
$closest = $account;
$shortest = $lev;
}
}
form_set_error('name', t("No user by that name! Did you mean <a href='#' id='suggest-login'>@user</a>?", array('@user' => $closest)));
drupal_add_js(
"$(document).ready(function() {
$('div.messages a').click(function(e) {
$('#edit-name').val('$closest');
});
});",
'inline'
);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment