app/django/contrib/localflavor/au/forms.py
changeset 54 03e267d67478
child 323 ff1a9aa48cfd
equal deleted inserted replaced
53:57b4279d8c4e 54:03e267d67478
       
     1 """
       
     2 Australian-specific Form helpers
       
     3 """
       
     4 
       
     5 from django.newforms import ValidationError
       
     6 from django.newforms.fields import Field, RegexField, Select, EMPTY_VALUES
       
     7 from django.newforms.util import smart_unicode
       
     8 from django.utils.translation import ugettext
       
     9 import re
       
    10 
       
    11 PHONE_DIGITS_RE = re.compile(r'^(\d{10})$')
       
    12 
       
    13 class AUPostCodeField(RegexField):
       
    14     """Australian post code field."""
       
    15     default_error_messages = {
       
    16         'invalid': ugettext('Enter a 4 digit post code.'),
       
    17     }
       
    18 
       
    19     def __init__(self, *args, **kwargs):
       
    20         super(AUPostCodeField, self).__init__(r'^\d{4}$',
       
    21             max_length=None, min_length=None, *args, **kwargs)
       
    22 
       
    23 class AUPhoneNumberField(Field):
       
    24     """Australian phone number field."""
       
    25     default_error_messages = {
       
    26         'invalid': u'Phone numbers must contain 10 digits.',
       
    27     }
       
    28 
       
    29     def clean(self, value):
       
    30         """
       
    31         Validate a phone number. Strips parentheses, whitespace and hyphens.
       
    32         """
       
    33         super(AUPhoneNumberField, self).clean(value)
       
    34         if value in EMPTY_VALUES:
       
    35             return u''
       
    36         value = re.sub('(\(|\)|\s+|-)', '', smart_unicode(value))
       
    37         phone_match = PHONE_DIGITS_RE.search(value)
       
    38         if phone_match:
       
    39             return u'%s' % phone_match.group(1)
       
    40         raise ValidationError(self.error_messages['invalid'])
       
    41 
       
    42 class AUStateSelect(Select):
       
    43     """
       
    44     A Select widget that uses a list of Australian states/territories as its
       
    45     choices.
       
    46     """
       
    47     def __init__(self, attrs=None):
       
    48         from au_states import STATE_CHOICES
       
    49         super(AUStateSelect, self).__init__(attrs, choices=STATE_CHOICES)