import re from django.core.validators import RegexValidator from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ from django.conf import settings from .common import ( validate_first_letter_not_number, end_with_letter_or_number, MinLengthValidator, MaxLengthValidator, NoDoubleSpecialValidator, DoesNotEndWithConfusingSuffixValidator ) class UsernameCharacterValidator(RegexValidator): regex = re.compile(r'^[a-zA-Z0-9-_\u4e00-\u9fa5]+$') message = _('should only contains: number、letter、chinese character、hyphen or underline.') class UsernameFirstCharacterValidator(RegexValidator): regex = re.compile(r'^[a-zA-Z_\u4e00-\u9fa5]') message = _('first letter should only be: letter、chinese character or underline.') def does_not_reserverd_usernames(username): if username.lower() in settings.RESERVED_USERNAMES: raise ValidationError(_('already used')) def validate_username(username, username_validators=None): errors = [] if username_validators is None: username_validators = [ MinLengthValidator(4), MaxLengthValidator(20), UsernameCharacterValidator(), UsernameFirstCharacterValidator(), NoDoubleSpecialValidator(), DoesNotEndWithConfusingSuffixValidator(), validate_first_letter_not_number, end_with_letter_or_number, does_not_reserverd_usernames ] for validator in username_validators: try: validator(username) except ValidationError as error: errors.append(error) if errors: raise ValidationError(errors)