Хотя вы можете использовать здесь регулярное выражение, я бы придерживался обычного Python:
from string import ascii_uppercase, ascii_lowercase, digits, punctuation
from pprint import pprint
character_classes = {'lowercase letter': ascii_lowercase,
'uppercase letter': ascii_uppercase,
'number': digits,
'special character': punctuation # change this if your idea of "special" characters is different
}
minimum_length = 8
def check_password(password):
long_enough = len(password) >= minimum_length
if not long_enough:
print(f'Your password needs to be at least {minimum_length} characters long!')
result = [{class_name: char in char_class for class_name, char_class in character_classes.items()} for char in password]
result_transposed = {class_name: [row[class_name] for row in result] for class_name in character_classes}
for char_class, values in result_transposed.items():
if not any(values):
# Instead of a print, you should raise a ValidationError here
print(f'Your password needs to have at least one {char_class}!')
return result_transposed
check_password('12j3dSe')
Выход:
Your password needs to be at least 8 characters long!
Your password needs to have at least one special character!
Это позволяет вам более гибко изменять требования к паролям, и в случае, если вы когда-нибудь захотите сказать «вам нужен X этого класса символов» ...