What I want
I’m working with a django
form and it takes a password input. I need to pass the input value for multiple regexes, which will test if:
- at least one character is a lowecase
- at least one character is a uppercase
- at least one character is a number
- at least one character is a especial character (symbol)
- 8 characters minimum
And I would like to know which of these conditions were fulfilled and which were not.
What I’ve done
JavaScript
x
19
19
1
def clean_password(self):
2
password = self.cleaned_data.get("password")
3
4
regexes = [
5
"[a-z]",
6
"[A-Z]",
7
"[0-9]",
8
#other regex...
9
]
10
11
# Make a regex that matches if any of our regexes match.
12
combined = "(" + ")|(".join(regexes) + ")"
13
14
if not re.match(combined, password):
15
print("Some regex matched!")
16
17
# i need to pass in ValidationError those regex that haven't match
18
raise forms.ValidationError('This password does not contain at least one number.')
19
Advertisement
Answer
While you can use a regex here, I would stick to normal Python:
JavaScript
1
26
26
1
from string import ascii_uppercase, ascii_lowercase, digits, punctuation
2
from pprint import pprint
3
4
character_classes = {'lowercase letter': ascii_lowercase,
5
'uppercase letter': ascii_uppercase,
6
'number': digits,
7
'special character': punctuation # change this if your idea of "special" characters is different
8
}
9
10
minimum_length = 8
11
12
def check_password(password):
13
long_enough = len(password) >= minimum_length
14
if not long_enough:
15
print(f'Your password needs to be at least {minimum_length} characters long!')
16
result = [{class_name: char in char_class for class_name, char_class in character_classes.items()} for char in password]
17
result_transposed = {class_name: [row[class_name] for row in result] for class_name in character_classes}
18
for char_class, values in result_transposed.items():
19
if not any(values):
20
# Instead of a print, you should raise a ValidationError here
21
print(f'Your password needs to have at least one {char_class}!')
22
23
return result_transposed
24
25
check_password('12j3dSe')
26
Output:
JavaScript
1
3
1
Your password needs to be at least 8 characters long!
2
Your password needs to have at least one special character!
3
This allows you to modify the password requirements in a more flexible fashion, and in case you ever want to say “you need X of this character class”…