UserNameConstraintValidator.php

Same filename and directory in other branches
  1. 8.9.x core/modules/user/src/Plugin/Validation/Constraint/UserNameConstraintValidator.php
  2. 10 core/modules/user/src/Plugin/Validation/Constraint/UserNameConstraintValidator.php
  3. 11.x core/modules/user/src/Plugin/Validation/Constraint/UserNameConstraintValidator.php

Namespace

Drupal\user\Plugin\Validation\Constraint

File

core/modules/user/src/Plugin/Validation/Constraint/UserNameConstraintValidator.php

View source
<?php

namespace Drupal\user\Plugin\Validation\Constraint;

use Drupal\user\UserInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the UserName constraint.
 */
class UserNameConstraintValidator extends ConstraintValidator {
    
    /**
     * {@inheritdoc}
     */
    public function validate($items, Constraint $constraint) {
        if (!isset($items) || !$items->value) {
            $this->context
                ->addViolation($constraint->emptyMessage);
            return;
        }
        $name = $items->first()->value;
        if (substr($name, 0, 1) == ' ') {
            $this->context
                ->addViolation($constraint->spaceBeginMessage);
        }
        if (substr($name, -1) == ' ') {
            $this->context
                ->addViolation($constraint->spaceEndMessage);
        }
        if (strpos($name, '  ') !== FALSE) {
            $this->context
                ->addViolation($constraint->multipleSpacesMessage);
        }
        if (preg_match('/[^\\x{80}-\\x{F7} a-z0-9@+_.\'-]/i', $name) || preg_match('/[\\x{80}-\\x{A0}' . '\\x{AD}' . '\\x{2000}-\\x{200F}' . '\\x{2028}-\\x{202F}' . '\\x{205F}-\\x{206F}' . '\\x{FEFF}' . '\\x{FF01}-\\x{FF60}' . '\\x{FFF9}-\\x{FFFD}' . '\\x{0}-\\x{1F}]/u', $name)) {
            $this->context
                ->addViolation($constraint->illegalMessage);
        }
        if (mb_strlen($name) > UserInterface::USERNAME_MAX_LENGTH) {
            $this->context
                ->addViolation($constraint->tooLongMessage, [
                '%name' => $name,
                '%max' => UserInterface::USERNAME_MAX_LENGTH,
            ]);
        }
    }

}

Classes

Title Deprecated Summary
UserNameConstraintValidator Validates the UserName constraint.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.