3

Just wondering if theres anyway to force some validation on the username? I have usernames being displayed locally, and therefore I'm trying to prevent email addresses being used. I have my client side validation set up with regex to prevent an email being used, but some users still seem to have been able to register with the email as there username (presumably they have JS disabled).

It would be nice to enforce that validation server side.

2 Answers 2

4

I don't know if there is anything natively in Craft to do this, but you could achieve it quite easily with a single file plugin:

public function init()
{
    craft()->on('users.onBeforeSaveUser', function(Event $event) {
        // Only do anything if it is a front end submission
        if(craft()->request->isSiteRequest())
        {
            $username = craft()->request->getPost('username', null);
            if($this->isEmail($username))
            {
                $event->params['user']->addErrors(array('username' => Craft::t('You cannot use an email')));
                $event->performAction = false;
            }
        }
    });
}
4
  • Thanks for this (apologies for the delay in responding, didn't get my notification!) I'll test this out shortly, thanks!
    – shorn
    Commented Apr 4, 2017 at 21:40
  • Hi, finally got round to trying this out. Getting an error though ...and its behaviors do not have a method or closure named "isEmail". - Any idea?
    – shorn
    Commented Apr 21, 2017 at 21:10
  • Yes, sorry should have clarified, the isEmail() method is to imply you are using your own implementation of how you check whether the passed string is an email address and return a boolean Commented Apr 22, 2017 at 9:42
  • No probs. Kind of figured and actually sorted it last night. Now validates against an alpha numeric regex and seems to be working fine! Thanks!
    – shorn
    Commented Apr 22, 2017 at 9:45
1

I ran into username validation because I had to migrate user names containing spaces (not allowed by default).

I ended up creating a custom Username validator and let composer's autoloader use that one instead of craft's default. You can easily add your own validation rules there.

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;
  }
}

Here is how to use the custom validator instead of the default one. Note that if Craft changes it's internals this might have to be adjusted.

https://io.24hoursmedia.com/tech-notes/allow-spaces-in-craft-cms-user-names

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.