from django.core.exceptions import ValidationError from django.utils.translation import gettext as _ class ComplexityValidator: """At least 12 characters with upper and lower case letters, a digit and a special character.""" min_length = 12 def validate(self, password: str, user: object = None) -> None: errors: list[ValidationError] = [] if len(password) < self.min_length: errors.append( ValidationError( _("The password must be at least %(min)d characters long.") % {"min": self.min_length}, code="password_too_short", ) ) checks = [ ( any(c.isupper() for c in password), _("The password must contain an upper case letter."), "password_no_upper", ), ( any(c.islower() for c in password), _("The password must contain a lower case letter."), "password_no_lower", ), ( any(c.isdigit() for c in password), _("The password must contain a digit."), "password_no_digit", ), ( any(not c.isalnum() and not c.isspace() for c in password), _("The password must contain a special character."), "password_no_special", ), ] errors += [ValidationError(message, code=code) for ok, message, code in checks if not ok] if errors: raise ValidationError(errors) def get_help_text(self) -> str: return _( "At least %(min)d characters, including upper and lower case letters, " "a digit and a special character." ) % {"min": self.min_length}