我有一个django表单,其中包含一个密码字段,我想验证它必须包含字母和数字组合的字段。
class AuthorizationForm(forms.Form):
email = forms.CharField()
password = forms.CharField(min_length=7)
我正在验证密码字段,如下所示:
def clean_password(self):
password = self.cleaned_data['password']
if not re.match(r'^[A-Za-z0-9]+$', password):
raise forms.ValidationError("Password should be a combination of Alphabets and Numbers")
这段代码对我不起作用,它允许abcdefghij
或123456789
或abcd123456
,因为我只想允许abcd123456
答案 0 :(得分:11)
您可以使用RegexValidator
的{{1}}。
尝试以下代码:
from django.core.validators import RegexValidator
class AuthorizationForm(forms.Form):
email = forms.CharField()
password = forms.CharField(min_length=7, validators=[RegexValidator('^(\w+\d+|\d+\w+)+$', message="Password should be a combination of Alphabets and Numbers")])
答案 1 :(得分:3)
正则表达式并不是必需的,您可以简单地使用字符串函数来执行此操作:
import string
def validate(password):
letters = set(string.ascii_letters)
digits = set(string.digits)
pwd = set(password)
return not (pwd.isdisjoint(letters) or pwd.isdisjoint(digits))
print(validate('123123')) # False
print(validate('asdfsdf')) # False
print(validate('12312sfdf')) # True