PageRenderTime 26ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/django/contrib/localflavor/il/forms.py

https://code.google.com/p/mango-py/
Python | 66 lines | 43 code | 7 blank | 16 comment | 1 complexity | ef611615d1932d77906fef5632156ff5 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. """
  2. Israeli-specific form helpers
  3. """
  4. import re
  5. from django.core.exceptions import ValidationError
  6. from django.core.validators import EMPTY_VALUES
  7. from django.forms.fields import RegexField, Field, EMPTY_VALUES
  8. from django.utils.checksums import luhn
  9. from django.utils.translation import ugettext_lazy as _
  10. # Israeli ID numbers consist of up to 8 digits followed by a checksum digit.
  11. # Numbers which are shorter than 8 digits are effectively left-zero-padded.
  12. # The checksum digit is occasionally separated from the number by a hyphen,
  13. # and is calculated using the luhn algorithm.
  14. #
  15. # Relevant references:
  16. #
  17. # (hebrew) http://he.wikipedia.org/wiki/%D7%9E%D7%A1%D7%A4%D7%A8_%D7%96%D7%94%D7%95%D7%AA_(%D7%99%D7%A9%D7%A8%D7%90%D7%9C)
  18. # (hebrew) http://he.wikipedia.org/wiki/%D7%A1%D7%A4%D7%A8%D7%AA_%D7%91%D7%99%D7%A7%D7%95%D7%A8%D7%AA
  19. id_number_re = re.compile(r'^(?P<number>\d{1,8})-?(?P<check>\d)$')
  20. class ILPostalCodeField(RegexField):
  21. """
  22. A form field that validates its input as an Israeli postal code.
  23. Valid form is XXXXX where X represents integer.
  24. """
  25. default_error_messages = {
  26. 'invalid': _(u'Enter a postal code in the format XXXXX'),
  27. }
  28. def __init__(self, *args, **kwargs):
  29. super(ILPostalCodeField, self).__init__(r'^\d{5}$', *args, **kwargs)
  30. def clean(self, value):
  31. if value not in EMPTY_VALUES:
  32. value = value.replace(" ", "")
  33. return super(ILPostalCodeField, self).clean(value)
  34. class ILIDNumberField(Field):
  35. """
  36. A form field that validates its input as an Israeli identification number.
  37. Valid form is per the Israeli ID specification.
  38. """
  39. default_error_messages = {
  40. 'invalid': _(u'Enter a valid ID number.'),
  41. }
  42. def clean(self, value):
  43. value = super(ILIDNumberField, self).clean(value)
  44. if value in EMPTY_VALUES:
  45. return u''
  46. match = id_number_re.match(value)
  47. if not match:
  48. raise ValidationError(self.error_messages['invalid'])
  49. value = match.group('number') + match.group('check')
  50. if not luhn(value):
  51. raise ValidationError(self.error_messages['invalid'])
  52. return value