/django/contrib/localflavor/us/forms.py

https://code.google.com/p/mango-py/ · Python · 122 lines · 84 code · 14 blank · 24 comment · 20 complexity · 7753d4cf7c4ab6166b4b16e84c0fe9ab MD5 · raw file

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