validators.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import re
  2. from django.core.exceptions import ValidationError
  3. from django.utils.translation import ungettext, ugettext_lazy as _
  4. from misago.banning.models import check_ban
  5. from misago.settings.settings import Settings
  6. def validate_username(value):
  7. value = unicode(value).strip()
  8. if len(value) < 3:
  9. raise ValidationError(_("Username cannot be shorter than 3 characters."))
  10. if len(value) > 12:
  11. raise ValidationError(_("Username cannot be longer than 12 characters."))
  12. if not re.search('^[0-9a-zA-Z]+$', value):
  13. raise ValidationError(_("Username can only contain letters and digits."))
  14. if check_ban(username=value):
  15. raise ValidationError(_("This username is forbidden."))
  16. def validate_password(value):
  17. value = unicode(value).strip()
  18. db_settings = Settings()
  19. if len(value) < db_settings['password_length']:
  20. raise ValidationError(ungettext(
  21. 'Correct password has to be at least one character long.',
  22. 'Correct password has to be at least %(count)d characters long.',
  23. db_settings['password_length']
  24. ) % {
  25. 'count': db_settings['password_length'],
  26. })
  27. for test in db_settings['password_complexity']:
  28. if test in ('case', 'digits', 'special'):
  29. if not re.search('[a-zA-Z]', value):
  30. raise ValidationError(_("Password must contain alphabetical characters."))
  31. if test == 'case':
  32. if not (re.search('[a-z]', value) and re.search('[A-Z]', value)):
  33. raise ValidationError(_("Password must contain characters that have different case."))
  34. if test == 'digits':
  35. if not re.search('[0-9]', value):
  36. raise ValidationError(_("Password must contain digits in addition to characters."))
  37. if test == 'special':
  38. if not re.search('[^0-9a-zA-Z]', value):
  39. raise ValidationError(_("Password must contain special (non alphanumerical) characters."))
  40. def validate_email(value):
  41. value = unicode(value).strip()
  42. if check_ban(email=value):
  43. raise ValidationError(_("This board forbids registrations using this e-mail address."))