Advertisement
horozov86

Validator password

Apr 1st, 2024 (edited)
695
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1. ДОПЪЛНИТЕЛНА ВАЛИДАЦИЯ НА ПАРОЛАТА НА USER (Server-side validation)
  2.  
  3. class MyHolidayUserCreationForm(auth_forms.UserCreationForm):
  4.     user = None
  5.     password1 = forms.CharField(
  6.         label="Password",
  7.         strip=False,
  8.         widget=forms.PasswordInput,
  9.         validators=[validate_password],
  10.     )
  11.     password2 = forms.CharField(
  12.         label="Password confirmation",
  13.         widget=forms.PasswordInput,
  14.         strip=False,
  15.     )
  16.  
  17.     class Meta(auth_forms.UserCreationForm.Meta):
  18.         model = UserModel
  19.         fields = ('email',)
  20.  
  21. ДОБАВЯМ МОЯ ВАЛИДАТОВ СЛЕД ВГРАДЕНИТЕ В settings.py - AUTH_PASSWORD_VALIDATORS:
  22.  
  23. AUTH_PASSWORD_VALIDATORS = [
  24.     {
  25.         'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
  26.     },
  27.     {
  28.         'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
  29.     },
  30.     {
  31.         'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
  32.     },
  33.     {
  34.         'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
  35.     },
  36.     {
  37.         'NAME': 'accounts.validators.validate_password',
  38.     },
  39. ]
  40.  
  41. valdators.py
  42.  
  43. from django.core.exceptions import ValidationError
  44.  
  45.  
  46. def validate_password(password):
  47.  
  48.     has_letter = False
  49.     has_digit = False
  50.     has_underscore = False
  51.  
  52.     for char in password:
  53.         if char.isalpha():
  54.             has_letter = True
  55.         elif char.isdigit():
  56.             has_digit = True
  57.         elif char == '_':
  58.             has_underscore = True
  59.  
  60.     if not has_letter:
  61.         raise ValidationError("Password must contain at least one letter.")
  62.  
  63.     if not has_digit:
  64.         raise ValidationError("Password must contain at least one digit.")
  65.  
  66.     if not has_underscore:
  67.         raise ValidationError("Password must contain at least one underscore.")
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement