Allow spaces in CraftCMS user names

Override the username validator in Craft CMS to allow spaces in usernames, or disallow other characters.


For some installs, you might want to allow spaces in Craft CMS usernames.

We had migrated a large user base with spaces allowed in the usernames, and we couldn't afford to change everybody's username.
Luckily, using composer, we can change the Craft Username validator and implement our own validation rules.

This is also very useful if you have your own custom rules, for example, require a digit in the username.


Create your own Username validator

This applies to Craft CMS 3.x.
First, you have to create your own username validator, and place it in this directory (relative to project root):
/craft-override/validators/UsernameValidator.php


<?php
// craft-override/validators/UsernameValidator.php
namespace craft\validators;

use yii\validators\Validator;

/**
 * Class UsernameValidator
 * Custom username validator allowing to override craft cms's username validator
 * (by www.24hoursmedia.com)
 */
class UsernameValidator extends Validator
{
    public function validateValue($value)
    {
        // your own validation rules here

        // (disabled) Don't allow whitespace in the username
        // if (preg_match('/\s+/', $value)) {
        //    return ['{attribute} cannot contain spaces.', []];
        // }

        return null;
    }
}

Modify composer.json to use the new Validator class

Then we can modify composer.json to load the classes in the craft-override directory as craft namespaced classes.
These classed have precedence over the classes in the vendor dir, so composer will just load the new validator.

Modify the autoload section in composer.json to include the line with "craft\\": "craft-override/":


{...

  "autoload": {
    "psr-4": {
      "modules\\": "modules/",
      "craft\\": "craft-override/"
    }
  },

...}

Regenerate a new classmap

Then, regenerate the classmaps and Craft CMS uses your own validator.


composer dumpautoload