python - 字母数字字符的django表单字段正则表达式验证

标签 python django django-forms

<分区>

我有一个 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")

这段代码对我不起作用,它允许 abcdefghij123456789abcd123456,因为我只想允许abcd123456

最佳答案

您可以使用 RegexValidator,它是 django builtin validator .

试试下面的代码:

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"
            )
        ]
    )

关于python - 字母数字字符的django表单字段正则表达式验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29865320/

相关文章:

django - 以表单形式访问管理模型实例

python - 有没有办法在 tensorflow 的时代中间停止训练?

python - 在 PyQt 中使用属性列表

python - Django related_table() 和 extra()

Django Imagefield 无法通过 ModelForm 正常工作

python - 如何处理一个 url 中的多个 View ?

python - docopt - 每个参数需要特定的数据类型

python - 评估预测的准确性

python - Django 多对多关系不保存

python - celery 没有同时执行任务