From 02b837d38a37239dcd7366e7735e12aff51ab790 Mon Sep 17 00:00:00 2001 From: Jannis Leidel Date: Sat, 7 May 2011 16:59:08 +0000 Subject: [PATCH] Fixed #8527 -- Made CAPostalCodeField more forgiving of the input format. Thanks to Claude Paroz. git-svn-id: http://code.djangoproject.com/svn/django/trunk@16175 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/contrib/localflavor/ca/forms.py | 18 +++++++++++++----- tests/regressiontests/forms/localflavor/ca.py | 8 ++++++-- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/django/contrib/localflavor/ca/forms.py b/django/contrib/localflavor/ca/forms.py index 788c9d0a6f..ac393de397 100644 --- a/django/contrib/localflavor/ca/forms.py +++ b/django/contrib/localflavor/ca/forms.py @@ -4,7 +4,7 @@ Canada-specific Form helpers from django.core.validators import EMPTY_VALUES from django.forms import ValidationError -from django.forms.fields import Field, RegexField, Select +from django.forms.fields import Field, CharField, Select from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ import re @@ -12,7 +12,7 @@ import re phone_digits_re = re.compile(r'^(?:1-?)?(\d{3})[-\.]?(\d{3})[-\.]?(\d{4})$') sin_re = re.compile(r"^(\d{3})-(\d{3})-(\d{3})$") -class CAPostalCodeField(RegexField): +class CAPostalCodeField(CharField): """ Canadian postal code field. @@ -25,9 +25,17 @@ class CAPostalCodeField(RegexField): 'invalid': _(u'Enter a postal code in the format XXX XXX.'), } - def __init__(self, max_length=None, min_length=None, *args, **kwargs): - super(CAPostalCodeField, self).__init__(r'^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ] \d[ABCEGHJKLMNPRSTVWXYZ]\d$', - max_length, min_length, *args, **kwargs) + postcode_regex = re.compile(r'^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ]) *(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$') + + def clean(self, value): + value = super(CAPostalCodeField, self).clean(value) + if value in EMPTY_VALUES: + return u'' + postcode = value.upper().strip() + m = self.postcode_regex.match(postcode) + if not m: + raise ValidationError(self.default_error_messages['invalid']) + return "%s %s" % (m.group(1), m.group(2)) class CAPhoneNumberField(Field): """Canadian phone number field.""" diff --git a/tests/regressiontests/forms/localflavor/ca.py b/tests/regressiontests/forms/localflavor/ca.py index bd31a5ce46..8a17ed26e7 100644 --- a/tests/regressiontests/forms/localflavor/ca.py +++ b/tests/regressiontests/forms/localflavor/ca.py @@ -45,13 +45,17 @@ class CALocalFlavorTests(LocalFlavorTestCase): 'T2S 2W7': 'T2S 2W7', 'T2S 2Z7': 'T2S 2Z7', 'T2Z 2H7': 'T2Z 2H7', - + 'T2S2H7' : 'T2S 2H7', + 't2s 2h7': 'T2S 2H7', + 't2s2h7' : 'T2S 2H7', + 't2s 2H7': 'T2S 2H7', + ' t2s 2H7 ': 'T2S 2H7', } invalid = { - 'T2S2H7' : error_format, 'T2S 2H' : error_format, '2T6 H8I': error_format, 'T2S2H' : error_format, + 't2s h8i': error_format, 90210 : error_format, 'W2S 2H3': error_format, 'Z2S 2H3': error_format,