PageRenderTime 38ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/django/contrib/localflavor/kw/forms.py

https://code.google.com/p/mango-py/
Python | 63 lines | 52 code | 4 blank | 7 comment | 0 complexity | 3c3ec6542e6624a4716d1915c61b27a2 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. """
  2. Kuwait-specific Form helpers
  3. """
  4. import re
  5. from datetime import date
  6. from django.core.validators import EMPTY_VALUES
  7. from django.forms import ValidationError
  8. from django.forms.fields import Field, RegexField
  9. from django.utils.translation import gettext as _
  10. id_re = re.compile(r'^(?P<initial>\d{1})(?P<yy>\d\d)(?P<mm>\d\d)(?P<dd>\d\d)(?P<mid>\d{4})(?P<checksum>\d{1})')
  11. class KWCivilIDNumberField(Field):
  12. """
  13. Kuwaiti Civil ID numbers are 12 digits, second to seventh digits
  14. represents the person's birthdate.
  15. Checks the following rules to determine the validty of the number:
  16. * The number consist of 12 digits.
  17. * The birthdate of the person is a valid date.
  18. * The calculated checksum equals to the last digit of the Civil ID.
  19. """
  20. default_error_messages = {
  21. 'invalid': _('Enter a valid Kuwaiti Civil ID number'),
  22. }
  23. def has_valid_checksum(self, value):
  24. weight = (2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2)
  25. calculated_checksum = 0
  26. for i in range(11):
  27. calculated_checksum += int(value[i]) * weight[i]
  28. remainder = calculated_checksum % 11
  29. checkdigit = 11 - remainder
  30. if checkdigit != int(value[11]):
  31. return False
  32. return True
  33. def clean(self, value):
  34. super(KWCivilIDNumberField, self).clean(value)
  35. if value in EMPTY_VALUES:
  36. return u''
  37. if not re.match(r'^\d{12}$', value):
  38. raise ValidationError(self.error_messages['invalid'])
  39. match = re.match(id_re, value)
  40. if not match:
  41. raise ValidationError(self.error_messages['invalid'])
  42. gd = match.groupdict()
  43. try:
  44. d = date(int(gd['yy']), int(gd['mm']), int(gd['dd']))
  45. except ValueError:
  46. raise ValidationError(self.error_messages['invalid'])
  47. if not self.has_valid_checksum(value):
  48. raise ValidationError(self.error_messages['invalid'])
  49. return value