I would want to disallow users register with user name having space or non-alphanumeric characters (2 bytes character. e.g Chinese characters). I think i have to hack the code of users.module. anyone could advise me or having any experience?

thanks a lot .

Comments

phdhiren’s picture

There is an admin setting for access rules
[localhost]/admin/user/rules/add

sisyphus’s picture

thank you.

i studied the access rules screen but i do not understand these two fields:
%: Matches any number of characters, even zero characters.
_: Matches exactly one character.

how to set the values to accomplish my requirement?

thanks a lot.

phdhiren’s picture

If you want to disallow space in the username
Access type: Deny
Rule type: Username
Mask: % %

See there is space between two '%'

Here % means any number of characters

- Another case If you don't want user to register with single character then you can put the Mask as
Access type: Deny
Rule type: Username
Mask: _

- Another case If you don't want user to register with two characters then you can put the Mask as
Access type: Deny
Rule type: Username
Mask: __

sisyphus’s picture

Thank you very much.

Now the requirement of disallowing users to use username with space is solved.

And I would like to disallow users to use non-alphanumeric characters (e.g. Japanese, Chinese.... ) in username too.

I saw these codes in users.module:

  if (ereg("[^\x80-\xF7 [:alnum:]@_.-]", $name)) return t('The username contains an illegal character.');
  if (preg_match('/[\x{80}-\x{A0}'.          // Non-printable ISO-8859-1 + NBSP
                   '\x{AD}'.                 // Soft-hyphen
                   '\x{2000}-\x{200F}'.      // Various space characters
                   '\x{2028}-\x{202F}'.      // Bidirectional text overrides
                   '\x{205F}-\x{206F}'.      // Various text hinting characters
                   '\x{FEFF}'.               // Byte order mark
                   '\x{FF01}-\x{FF60}'.      // Full-width latin
                   '\x{FFF9}-\x{FFFD}'.      // Replacement characters
                   '\x{0}]/u',               // NULL byte
                   $name)) {
    return t('The username contains an illegal character.');

What codes should be added to this list to disallow non-alphanumeric characters to form the username?

Thanks a lot.

chadhester’s picture

This is a great thread, and I agree that this might need to be expanded a bit to get tighter control over valid characters/strings. Perhaps this module deserves a bit of a regular expressions upgrade, with several example rules for the common user. Just a thought.

The main motivation I would have for such tight control is integrating with other systems that would use the same or similar login credentials.

__________
Regards,
Chad Hester

benone’s picture

% % is not working. I can still register a username containing spaces.
Did you check it ?

fehin’s picture

It worked when I created a seperate rule for it. Don't join it with other rules.

Babalu’s picture

i would like to disallow usernames with admin in them eg. admin1
how can i do that without blocking admin

novice.drupaler’s picture

add these rules

disallow username %admin%
allow username admin

mr.andrey’s picture

Is there a way to deny all, and only allow the following characters?

[a-z][A-Z][0-9]_

People are registering on a public site and specifying their email as the username, which of course will be splattered with spam. Then there's passing usernames in URL to views... and if you want to dynamically add usernames to a view filter with AND/OR +/- syntax, that might break things as well...

I would really like to avoid all confusion and only allow alphanumeric and underscore characters.

Best,
Andrey.

fehin’s picture

You can disallow the use of "@" in usernames.

benone’s picture

SUBSCRIBE to this: [a-z][A-Z][0-9]_
how to disable all accents and special characters in username ?

benone’s picture

OK, its easy:

in user.module find a line:

function user_validate_name($name) {

and add this below this line:

  if (strlen($name) < 5) return t('The username is too short. It must be 5 characters or more.');
  if (!preg_match('/^[a-zA-Z0-9-]+$/u', $name)) return t('The username contains an illegal character. You can use only letters, digits and - . Do not use accents.');
  if (substr($name, 0, 1) == '-') return t('The username cannot begin with - .');
  if (substr($name, -1) == '-') return t('The username cannot end with - .');

What it does for Username:

- use only a-z A-Z 0-9 and - (dash)
- no accents like: ç , ą , ę , etc...
- no spaces
- no - (dash) in the beginnig or in the end of username
- minimum length of username is 5 characters

After that I removed all access rules in my drupal setup. This is quicker and nicer and has more options. The only problem, you need to hack user.module , so remember to make a copy of that file and provide those changes after every drupal core update.

I dont know how to create a custom module with those options, if anybody has the idea, would be great.

Enjoy clean and easy usernames on your site ;)

cehfisher’s picture

Thanks benone! I actually just added the code and it worked perfectly!

One question I do have (for everyone) - what do you do about users who already have a username in place that has special characters or spaces? Can they still login? Also, I can send an email to all of the users asking them to update their username (if applicable), but it is doubtful that many will do this. Any ideas?

benone’s picture

yeah, thats a good question.
i would change them by hand and email each about new username.
but if you have more ... huh that might be hard..

cehfisher’s picture

Just wanted you to know that users that have special characters in their usernames can still log-in, if they set-up their account before this code is added. All new users have to follow the special character rules when setting up their accounts. The old users are "grandfathered" in, so to speak.

I still haven't come up with a reasonable way to get the original users update their usernames, so for now I'm just ignoring that point. Thanks again for the useful code!

khorby’s picture

Thanks for this code, benone! This is something that should become standard in all drupal installed, it's really helped me a lot!

hurricane_cgn’s picture

i also like to implement a white-list for the allowed characters in the username. hacking the user.module file works for me, but i'm wondering, if there is a better (more drupal) way than hacking the core.

did anyone try to alter the user-registration and user-edit form yet? (e.g. own element specific validation function for the username)

sagar ramgade’s picture

Yes i had tried with hook_user

hook_user($op, &$edit, &$account, $category = null){
switch ($op) {
      case 'validate':
              //checks if username not empty
               if($edit['name']){
               //Check your condition here
               ........
              form_set_error('name', t('Username cannot be used, please try again.'));
              }
              break;
   }
}

Hope this helps

Acquia certified Developer, Back end and Front specialist
Need help? Please use my contact form

sarmiluv’s picture

I don't know why drupal does not makes it easier to do. Here is what I want. Please help:

Only following should be allowed for username.

Minimum characters: 4
Maximum characters: 15
A - Z
a - z
0 - 9
. (period)
_ (underscore)
Should not start or end with . (period) and _ (underscore)
Should not start with numbers (o - 9)

sagar ramgade’s picture

Hi,
Create a module which will hook_user to validate the username. The function below will match your needs. Please check and confirm.

<?php
function mymodule_user($op, &$edit, &$account, $category = null){
    switch ($op) {
      case 'validate':
        $name  = $edit['name'];
        if (strlen($name) < 4 || strlen($name) > 15) return t('The username is too short. It must be more than 4 characters and less than 15 characters.');
          if (!preg_match('/^[a-zA-Z0-9_.]+$/u', $name)) return t('The username contains an illegal character. You can use only letters, digits, . and _ . Do not use accents.');
          if (substr($name, 0, 1) == '_') return t('The username cannot begin with _ .');
          if (substr($name, -1) == '_') return t('The username cannot end with _ .');
          if (substr($name, 0, 1) == '.') return t('The username cannot begin with . .');
          if (substr($name, -1) == '.') return t('The username cannot end with . .');
          $int = substr($name, 0, 1);
          if(is_int($int)) return t('The username cannot start with a number');  
}

?>

Regards
Sagar

Acquia certified Developer, Back end and Front specialist
Need help? Please use my contact form

sarmiluv’s picture

Sagar, I really don't know how to create a module. I have no knowledge in coding. Can you help me with that too?

sagar ramgade’s picture

Hi,
here are the files you need to have for above module :
username_validate.module file :

<?php

// $Id: username_validate.module,v 1.0 2010/11/25 10:37:00 sagar $

//Implementation of hook_user
function username_validate_user($op, &$edit, &$account, $category = null){
    switch ($op) {
      case 'validate':
        $name  = $edit['name'];
        if (strlen($name) < 4 || strlen($name) > 15) return t('The username is too short. It must be more than 4 characters and less than 15 characters.');
          if (!preg_match('/^[a-zA-Z0-9_.]+$/u', $name)) return t('The username contains an illegal character. You can use only letters, digits, . and _ . Do not use accents.');
          if (substr($name, 0, 1) == '_') return t('The username cannot begin with _ .');
          if (substr($name, -1) == '_') return t('The username cannot end with _ .');
          if (substr($name, 0, 1) == '.') return t('The username cannot begin with . .');
          if (substr($name, -1) == '.') return t('The username cannot end with . .');
          $int = substr($name, 0, 1);
          if(is_int($int)) return t('The username cannot start with a number'); 
}

username_validate.info file :

; $Id: username_validate.info,v 1.0 2010/11/25 10:37:54 sagar $
name = Username Validate
description = Custom module for User name validation
core = 6.x

you need place these files under sites/all/modules/username_validate directory.
Hope this helps.

Regards
Sagar

Acquia certified Developer, Back end and Front specialist
Need help? Please use my contact form

sarmiluv’s picture

I created a module and uploaded in modules directory but I don't see it listed in admin/build/modules. So, I am not able to enable it. Please suggest how I can make it work.

sagar ramgade’s picture

Hi,

My fault i missed one '}' in the .module file.
username_validate.module :

<?php

// $Id: username_validate.module,v 1.0 2010/11/25 10:37:00 sagar $

//Implementation of hook_user
function username_validate_user($op, &$edit, &$account, $category = null){
    switch ($op) {
      case 'validate':
        $name  = $edit['name'];
        if (strlen($name) < 4 || strlen($name) > 15) return t('The username is too short. It must be more than 4 characters and less than 15 characters.');
          if (!preg_match('/^[a-zA-Z0-9_.]+$/u', $name)) return t('The username contains an illegal character. You can use only letters, digits, . and _ . Do not use accents.');
          if (substr($name, 0, 1) == '_') return t('The username cannot begin with _ .');
          if (substr($name, -1) == '_') return t('The username cannot end with _ .');
          if (substr($name, 0, 1) == '.') return t('The username cannot begin with . .');
          if (substr($name, -1) == '.') return t('The username cannot end with . .');
          $int = substr($name, 0, 1);
          if(is_int($int)) return t('The username cannot start with a number'); 
    }
}

username_validate.info

; $Id: username_validate.info,v 1.0 2010/11/25 10:37:54 sagar $
name = Username Validate
description = Custom module for User name validation
core = 6.x

place these files under yoursite/sites/all/modules/username_validate

Regards
Sagar

Acquia certified Developer, Back end and Front specialist
Need help? Please use my contact form

sarmiluv’s picture

Its not working again. Please check. I am using drupal 6.x.

mula’s picture

It's not working for me too. I wrote alternate code with hook_form_alter.

/**
 * Implementation of hook_form_alter().
 */
function username_validate_form_alter(&$form, &$form_state, $form_id) {
  if (in_array($form_id, array('user_register', 'user_edit', 'user_profile_form'))) {
    $form['#validate'][] = 'username_validate_username_validate';
  }
}

function username_validate_username_validate($form, &$form_state) {
  $error = _username_validate_username_validate($form_state['values']['name']);
  if (!empty($error)) {
    form_set_error('name', $error);
  }
}

function _username_validate_username_validate($name) {
  if (strlen($name) < 4 || strlen($name) > 15) return t('The username is too short. It must be more than 4 characters and less than 15 characters.');
  if (!preg_match('/^[a-zA-Z0-9_.]+$/u', $name)) return t('The username contains an illegal character. You can use only letters, digits, . and _ . Do not use accents.');
  if (substr($name, 0, 1) == '_') return t('The username cannot begin with _ .');
  if (substr($name, -1) == '_') return t('The username cannot end with _ .');
  if (substr($name, 0, 1) == '.') return t('The username cannot begin with . .');
  if (substr($name, -1) == '.') return t('The username cannot end with . .');
  $int = substr($name, 0, 1);
  if(is_int($int)) return t('The username cannot start with a number');
}
Sepero’s picture

Also, it would be helpful to let the user know what they are allowed to use in their name before registering. Otherwise it will still say that Spaces are allowed, as well as other things. You can edit the username description with this variable $form['account']['name']['#description']. Here's what my hook_alter function looks like.

function username_validate_form_alter(&$form, &$form_state, $form_id) {
  if (in_array($form_id, array('user_register', 'user_edit', 'user_profile_form'))) {
    $form['#validate'][] = 'username_validate_username_validate';
    $form['account']['name']['#description'] = "Lowercase letters, numbers, and underscore_ allowed.";
  }
}
jenyum’s picture

I would like to disallow user names with more than one number. Most spambots seem to create user names with four or more numbers in them, so this would take care of the vast majority of those registrations. (I have a captcha, Mollom, Spambot and Bad Behavior, but I still get 20-30 spam registrations a day)

Any idea how to implement this?

irohit786’s picture

That is exactly I was looking for..thank you people..