Advertisement
horozov86

validate password - change form.py

Mar 26th, 2024
433
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. from django.contrib.auth.forms import UserCreationForm
  2. from django.core.exceptions import ValidationError
  3. from django.utils.translation import gettext_lazy as _
  4. from django.contrib.auth import get_user_model
  5.  
  6. UserModel = get_user_model()
  7.  
  8. class MyHolidayUserCreationForm(UserCreationForm):
  9.     user = None
  10.  
  11.     def clean_password1(self):
  12.         password1 = self.cleaned_data.get("password1")
  13.         self.validate_password(password1)
  14.         return password1
  15.  
  16.     def validate_password(self, password):
  17.         if len(password) < 6:
  18.             raise ValidationError(_("Password must be at least 6 characters long."))
  19.  
  20.         has_letter = False
  21.         has_digit = False
  22.         has_underscore = False
  23.  
  24.         for char in password:
  25.             if char.isalpha():
  26.                 has_letter = True
  27.             elif char.isdigit():
  28.                 has_digit = True
  29.             elif char == '_':
  30.                 has_underscore = True
  31.  
  32.         if not has_letter:
  33.             raise ValidationError(_("Password must contain at least one letter."))
  34.  
  35.         if not has_digit:
  36.             raise ValidationError(_("Password must contain at least one digit."))
  37.  
  38.         if not has_underscore:
  39.             raise ValidationError(_("Password must contain at least one underscore."))
  40.  
  41.     class Meta(UserCreationForm.Meta):
  42.         model = UserModel
  43.         fields = ('email',)
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement