PageRenderTime 61ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/site/newsite/site-geraldo/django/contrib/localflavor/us/forms.py

https://github.com/CubicERP/geraldo
Python | 112 lines | 101 code | 6 blank | 5 comment | 3 complexity | e99ad60534a531e8f4022bb151546b90 MD5 | raw file
Possible License(s): LGPL-3.0, BSD-3-Clause
  1. """
  2. USA-specific Form helpers
  3. """
  4. from django.forms import ValidationError
  5. from django.forms.fields import Field, RegexField, Select, EMPTY_VALUES
  6. from django.utils.encoding import smart_unicode
  7. from django.utils.translation import ugettext_lazy as _
  8. import re
  9. phone_digits_re = re.compile(r'^(?:1-?)?(\d{3})[-\.]?(\d{3})[-\.]?(\d{4})$')
  10. ssn_re = re.compile(r"^(?P<area>\d{3})[-\ ]?(?P<group>\d{2})[-\ ]?(?P<serial>\d{4})$")
  11. class USZipCodeField(RegexField):
  12. default_error_messages = {
  13. 'invalid': _('Enter a zip code in the format XXXXX or XXXXX-XXXX.'),
  14. }
  15. def __init__(self, *args, **kwargs):
  16. super(USZipCodeField, self).__init__(r'^\d{5}(?:-\d{4})?$',
  17. max_length=None, min_length=None, *args, **kwargs)
  18. class USPhoneNumberField(Field):
  19. default_error_messages = {
  20. 'invalid': u'Phone numbers must be in XXX-XXX-XXXX format.',
  21. }
  22. def clean(self, value):
  23. super(USPhoneNumberField, self).clean(value)
  24. if value in EMPTY_VALUES:
  25. return u''
  26. value = re.sub('(\(|\)|\s+)', '', smart_unicode(value))
  27. m = phone_digits_re.search(value)
  28. if m:
  29. return u'%s-%s-%s' % (m.group(1), m.group(2), m.group(3))
  30. raise ValidationError(self.error_messages['invalid'])
  31. class USSocialSecurityNumberField(Field):
  32. """
  33. A United States Social Security number.
  34. Checks the following rules to determine whether the number is valid:
  35. * Conforms to the XXX-XX-XXXX format.
  36. * No group consists entirely of zeroes.
  37. * The leading group is not "666" (block "666" will never be allocated).
  38. * The number is not in the promotional block 987-65-4320 through
  39. 987-65-4329, which are permanently invalid.
  40. * The number is not one known to be invalid due to otherwise widespread
  41. promotional use or distribution (e.g., the Woolworth's number or the
  42. 1962 promotional number).
  43. """
  44. default_error_messages = {
  45. 'invalid': _('Enter a valid U.S. Social Security number in XXX-XX-XXXX format.'),
  46. }
  47. def clean(self, value):
  48. super(USSocialSecurityNumberField, self).clean(value)
  49. if value in EMPTY_VALUES:
  50. return u''
  51. match = re.match(ssn_re, value)
  52. if not match:
  53. raise ValidationError(self.error_messages['invalid'])
  54. area, group, serial = match.groupdict()['area'], match.groupdict()['group'], match.groupdict()['serial']
  55. # First pass: no blocks of all zeroes.
  56. if area == '000' or \
  57. group == '00' or \
  58. serial == '0000':
  59. raise ValidationError(self.error_messages['invalid'])
  60. # Second pass: promotional and otherwise permanently invalid numbers.
  61. if area == '666' or \
  62. (area == '987' and group == '65' and 4320 <= int(serial) <= 4329) or \
  63. value == '078-05-1120' or \
  64. value == '219-09-9999':
  65. raise ValidationError(self.error_messages['invalid'])
  66. return u'%s-%s-%s' % (area, group, serial)
  67. class USStateField(Field):
  68. """
  69. A form field that validates its input is a U.S. state name or abbreviation.
  70. It normalizes the input to the standard two-leter postal service
  71. abbreviation for the given state.
  72. """
  73. default_error_messages = {
  74. 'invalid': u'Enter a U.S. state or territory.',
  75. }
  76. def clean(self, value):
  77. from us_states import STATES_NORMALIZED
  78. super(USStateField, self).clean(value)
  79. if value in EMPTY_VALUES:
  80. return u''
  81. try:
  82. value = value.strip().lower()
  83. except AttributeError:
  84. pass
  85. else:
  86. try:
  87. return STATES_NORMALIZED[value.strip().lower()].decode('ascii')
  88. except KeyError:
  89. pass
  90. raise ValidationError(self.error_messages['invalid'])
  91. class USStateSelect(Select):
  92. """
  93. A Select widget that uses a list of U.S. states/territories as its choices.
  94. """
  95. def __init__(self, attrs=None):
  96. from us_states import STATE_CHOICES
  97. super(USStateSelect, self).__init__(attrs, choices=STATE_CHOICES)