标签:python django-forms python-regex
我想要的是
我正在使用django表单,它需要输入密码.我需要传递多个正则表达式的输入值,这将测试是否:
>至少一个字符是小写
>至少一个字符是大写
>至少一个字符是数字
>至少一个字符是特殊字符(符号)
至少8个字符
我想知道其中哪些条件已满足,哪些没有.
我做了什么
def clean_password(self):
password = self.cleaned_data.get("password")
regexes = [
"[a-z]",
"[A-Z]",
"[0-9]",
#other regex...
]
# Make a regex that matches if any of our regexes match.
combined = "(" + ")|(".join(regexes) + ")"
if not re.match(combined, password):
print("Some regex matched!")
# i need to pass in ValidationError those regex that haven't match
raise forms.ValidationError('This password does not contain at least one number.')
解决方法:
虽然您可以在此处使用正则表达式,但我会坚持使用普通的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”.
标签:python,django-forms,python-regex 来源: https://codeday.me/bug/20191013/1905218.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。