如何在django auth密码验证器旁边使用自定义密码验证器?

时间:2017-05-11 12:32:03

标签: python django validation passwords registration

正如上面提到的问题,我将尝试在注册过程中使用某个额外的规则来验证密码。 如果密码至少有一个数字,一个字母和一个特殊字符,则额外规则应该是密码验证。

我解决这个问题的方法我创建了一个名为validators.py的文件。

from django.core.exceptions import ValidationError

class CustomPasswortValidator:

    def validate(value):

      # check for digit
      if not any(char.isdigit() for char in value):
          raise ValidationError(_('Password must contain at least 1 digit.'))

      # check for letter
      if not any(char.isalpha() for char in value):
          raise ValidationError(_('Password must contain at least 1 letter.'))

      # check for special character
      special_characters = "[~\!@#\$%\^&\*\(\)_\+{}\":;'\[\]]"
      if not any(char in special_characters for char in value):
        raise ValidationError(_('Password must contain at least 1 letter.'))

我的自定义注册表单如下所示:

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User


class RegistrationForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, required=False,                                         
                                 help_text='Optional.')
    last_name = forms.CharField(max_length=30, required=False, 
                                 help_text='Optional.')
    email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', )

我不知道如何告诉django,我的自定义密码验证器应该在django AUTH_PASSWORD_VALIDATORS旁边使用。

0 个答案:

没有答案