| 1 | """ |
| 2 | Canada-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 gettext |
| 9 | import re |
| 10 | |
| 11 | PHONE_DIGITS_RE = re.compile(r'^(\d{10})$') |
| 12 | |
| 13 | class CAPostCodeField(RegexField): |
| 14 | """Canadian post code field.""" |
| 15 | def __init__(self, *args, **kwargs): |
| 16 | super(CAPostCodeField, self).__init__(r'^[A-Z]\d[A-Z] \d[A-Z]\d$', |
| 17 | max_length=None, min_length=None, |
| 18 | error_message=gettext(u'Enter correct postal code.'), |
| 19 | *args, **kwargs) |
| 20 | |
| 21 | class CAPhoneNumberField(Field): |
| 22 | """Canadian phone number field.""" |
| 23 | def clean(self, value): |
| 24 | """Validate a phone number. Strips parentheses, whitespace and |
| 25 | hyphens. |
| 26 | """ |
| 27 | super(CAPhoneNumberField, self).clean(value) |
| 28 | if value in EMPTY_VALUES: |
| 29 | return u'' |
| 30 | value = re.sub('(\(|\)|\s+|-)', '', smart_unicode(value)) |
| 31 | phone_match = PHONE_DIGITS_RE.search(value) |
| 32 | if phone_match: |
| 33 | return u'%s' % phone_match.group(1) |
| 34 | raise ValidationError(u'Phone numbers must contain 10 digits.') |
| 35 | |
| 36 | class CAProvinceSelect(Select): |
| 37 | """ |
| 38 | A Select widget that uses a list of Canadian provinces and |
| 39 | territories as its choices. |
| 40 | """ |
| 41 | def __init__(self, attrs=None): |
| 42 | from ca_provinces import PROVINCE_CHOICES # relative import |
| 43 | super(CAStateSelect, self).__init__(attrs, choices=PROVINCE_CHOICES) |