PageRenderTime 102ms CodeModel.GetById 40ms app.highlight 10ms RepoModel.GetById 50ms app.codeStats 0ms

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

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