Drupal 7 开发内部培训资料, 分头诗人

如何禁止用户在注册用户名时使用“空格”?

赞成!
0
否决!

试了很多模块,都是只能禁止使用指定的字符,但是无法禁止“空格”,有什么办法解决吗

2 个回答

赞成!
0
否决!

试一下增加一个模块,修改一下验证方式,大概帮你写一下

function my_module_my_form_validate($form, &$form_state) {

//birth year
  $year_of_birth = $form_state['values']['year_of_birth'];
  if ($year_of_birth && ($year_of_birth < 1900 || $year_of_birth > 2000)) {
    form_set_error('year_of_birth', 'Enter a year between 1900 and 2000.');
  }

//username
  $username = $form_state['values']['uname'];   
  if (strpos($username,' ') > 0 || strpos($username,'.') > 0 || strpos($username,'-') > 0 || strpos($username,'_') > 0 || strpos($username, "'") !== FALSE ){
    form_set_error('uname','User name cannot contain spaces . - _ ' . chr(39)  );
  }  
}
赞成!
0
否决!

可以安装username_check 模块,然后修改username_check模块的判断代码

//implement hook_form_FORM_ID_alter
function custom_form_user_register_form_alter(&$form, $form_state, $form_id) {
  //define validation function
  $form['#validate'][] = 'my_user_register_validate';
  //overwrite the username help text
  $form['account']['name']['#description'] = 'Username has to be between 5-15 characters long and can only contain letters and numbers';
}

function my_user_register_validate($form, &$form_state) {

  $output['error'] = FALSE;
  $username = $form_state['input']['name'];
  $password = $form_state['input']['pass']['pass1'];

  if (strlen($username) < 5 || strlen($username) > 15) {
    $output['error'] = TRUE;
    $output['msg'] = t('The username has to be between 5 and 15 characters long. ');
  }
  if (strpos($username,' ') > 0 || strpos($username,'.') > 0 || strpos($username,'-') > 0 || strpos($username,'_') > 0 || strpos($username, "'") !== FALSE ){
    $output['error'] = TRUE;
    $output['msg'] = t('Username cannot contain spaces . - _ ' . chr(39)  );
  }

//display username errors
  if ($output['error']){
    //drupal_set_message( $output['msg'], 'error');
    form_set_error('name', $output['msg']);
  }
}