Use Email Or Username To Login But Allow Empty Username

In my version of user component it’s possible to login using email or username. During registration username is allowed to be empty but if it’s not empty I’d like it to be unique. What is a neat way to implement this?

I think in case of empty username it might be a good idea to populate it with user id and require at least one letter in username filled in by a user. This way the field ‘username’ in db can be UNIQUE. But user id is allocated by db so I will have to update the record immediately after saving or use db triggers.

If you’re using MySQL, a field can be unique and have multiple NULL values. I’d handle this by setting up a nullable field in the database with a unique constraint, then use rules like the following:

    array('username', 'default', 'value'=>null, 'setOnEmpty'=>true),

    array('username', 'unique', 'allowEmpty'=>true),

I think that’ll work for you, but if not, you should be able to tweak the concept.


Here’s how I did it: DB field username UNIQUE NULL DEFAULT NULL


	array('username', 'length', 'max'=>32, 'min' => 5,'message' => Yii::app()->user->t("Incorrect username (length between 5 and 32 characters).")),

	array('username', 'default', 'value'=>null, 'setOnEmpty'=>true),

	array('username', 'unique', 'message' => Yii::app()->user->t("This user's name already exists.")),

	array('username', 'match', 'pattern' => '/^(?!_)[A-Za-z0-9_]*(?=[A-Za-z])[A-Za-z0-9_]*$/u','message' => Yii::app()->user->t("Please use Latin letters, numbers or «_». At least 1 letter.")

(?!) in regex means I don’t want usernames starting with «». And I use positive look forward (?=[A-Za-z]) to ensure usernames contain at least 1 letter. This way it will be possible to serve users’ pages in 2 ways: site/user/<id> or site/user/<username> without having to deal with usernames coinciding with ids.