PageRenderTime 4ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/django/contrib/localflavor/za/forms.py

https://code.google.com/p/mango-py/
Python | 60 lines | 43 code | 9 blank | 8 comment | 3 complexity | 23ee2c920aa9688323f57ac8b8d63ea3 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. """
  2. South Africa-specific Form helpers
  3. """
  4. from django.core.validators import EMPTY_VALUES
  5. from django.forms import ValidationError
  6. from django.forms.fields import Field, RegexField
  7. from django.utils.checksums import luhn
  8. from django.utils.translation import gettext as _
  9. import re
  10. from datetime import date
  11. id_re = re.compile(r'^(?P<yy>\d\d)(?P<mm>\d\d)(?P<dd>\d\d)(?P<mid>\d{4})(?P<end>\d{3})')
  12. class ZAIDField(Field):
  13. """A form field for South African ID numbers -- the checksum is validated
  14. using the Luhn checksum, and uses a simlistic (read: not entirely accurate)
  15. check for the birthdate
  16. """
  17. default_error_messages = {
  18. 'invalid': _(u'Enter a valid South African ID number'),
  19. }
  20. def clean(self, value):
  21. super(ZAIDField, self).clean(value)
  22. if value in EMPTY_VALUES:
  23. return u''
  24. # strip spaces and dashes
  25. value = value.strip().replace(' ', '').replace('-', '')
  26. match = re.match(id_re, value)
  27. if not match:
  28. raise ValidationError(self.error_messages['invalid'])
  29. g = match.groupdict()
  30. try:
  31. # The year 2000 is conveniently a leapyear.
  32. # This algorithm will break in xx00 years which aren't leap years
  33. # There is no way to guess the century of a ZA ID number
  34. d = date(int(g['yy']) + 2000, int(g['mm']), int(g['dd']))
  35. except ValueError:
  36. raise ValidationError(self.error_messages['invalid'])
  37. if not luhn(value):
  38. raise ValidationError(self.error_messages['invalid'])
  39. return value
  40. class ZAPostCodeField(RegexField):
  41. default_error_messages = {
  42. 'invalid': _(u'Enter a valid South African postal code'),
  43. }
  44. def __init__(self, *args, **kwargs):
  45. super(ZAPostCodeField, self).__init__(r'^\d{4}$',
  46. max_length=None, min_length=None, *args, **kwargs)