Ticket #8527: ca-form.diff

File ca-form.diff, 2.7 KB (added by Doug Harris, 16 years ago)

Patch and tests

  • django/contrib/localflavor/ca/forms.py

     
    33"""
    44
    55from django.forms import ValidationError
    6 from django.forms.fields import Field, RegexField, Select, EMPTY_VALUES
     6from django.forms.fields import Field, CharField, Select, EMPTY_VALUES
    77from django.forms.util import smart_unicode
    88from django.utils.translation import ugettext_lazy as _
    99import re
     
    1111phone_digits_re = re.compile(r'^(?:1-?)?(\d{3})[-\.]?(\d{3})[-\.]?(\d{4})$')
    1212sin_re = re.compile(r"^(\d{3})-(\d{3})-(\d{3})$")
    1313
    14 class CAPostalCodeField(RegexField):
     14class CAPostalCodeField(CharField):
    1515    """Canadian postal code field."""
    1616    default_error_messages = {
    1717        'invalid': _(u'Enter a postal code in the format XXX XXX.'),
    1818    }
    1919
    20     def __init__(self, *args, **kwargs):
    21         super(CAPostalCodeField, self).__init__(r'^[ABCEGHJKLMNPRSTVXYZ]\d[A-Z] \d[A-Z]\d$',
    22             max_length=None, min_length=None, *args, **kwargs)
     20    postcode_regex = re.compile(r'^([ABCEGHJKLMNPRSTVXYZ]\d[A-Z]) *(\d[A-Z]\d)$')
    2321
     22    def clean(self, value):
     23        value = super(CAPostalCodeField, self).clean(value)
     24        if value == u'':
     25            return value
     26        postcode = value.upper().strip()
     27        m = self.postcode_regex.match(postcode)
     28        if not m:
     29            raise ValidationError(self.default_error_messages['invalid'])
     30
     31        return "%s %s" % (m.group(1), m.group(2))
     32
    2433class CAPhoneNumberField(Field):
    2534    """Canadian phone number field."""
    2635    default_error_messages = {
  • tests/regressiontests/forms/localflavor/ca.py

     
    3737>>> f.clean('T2S 2H7')
    3838u'T2S 2H7'
    3939>>> f.clean('T2S2H7')
    40 Traceback (most recent call last):
    41 ...
    42 ValidationError: [u'Enter a postal code in the format XXX XXX.']
     40u'T2S 2H7'
    4341>>> f.clean('T2S 2H')
    4442Traceback (most recent call last):
    4543...
     
    6058u''
    6159>>> f.clean('')
    6260u''
     61>>> f.clean('t2s h8i')
     62Traceback (most recent call last):
     63...
     64ValidationError: [u'Enter a postal code in the format XXX XXX.']
     65>>> f.clean('t2s 2h7')
     66u'T2S 2H7'
     67>>> f.clean('t2s2h7')
     68u'T2S 2H7'
     69>>> f.clean('t2s2H7')
     70u'T2S 2H7'
     71>>> f.clean('t2s            2H7')
     72u'T2S 2H7'
     73>>> f.clean('  t2s            2H7')
     74u'T2S 2H7'
     75>>> f.clean('  t2s 2H7  ')
     76u'T2S 2H7'
     77>>> f.clean('  T2S 2H7  ')
     78u'T2S 2H7'
    6379
    6480# CAPhoneNumberField ##########################################################
    6581
Back to Top