summaryrefslogtreecommitdiff
path: root/django
diff options
context:
space:
mode:
authorMalcolm Tredinnick <malcolm.tredinnick@gmail.com>2007-12-19 04:43:47 +0000
committerMalcolm Tredinnick <malcolm.tredinnick@gmail.com>2007-12-19 04:43:47 +0000
commita35ca605d62d1b97eb595dcaa27b0904a0fe2182 (patch)
tree03ab93cd5b351d46c9fa8c6b495b5afd738e22d7 /django
parentaec96649f0c107c16721d4c56267f0acc990d58f (diff)
Fixed #5670 -- Changed the validation of the UK postcode widget to allow for easier input. Normalisation still returns the same things as previously. Patch from scott@staplefish.com.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@6952 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'django')
-rw-r--r--django/contrib/localflavor/uk/forms.py28
1 files changed, 22 insertions, 6 deletions
diff --git a/django/contrib/localflavor/uk/forms.py b/django/contrib/localflavor/uk/forms.py
index 68e15aac38..52cd7ad232 100644
--- a/django/contrib/localflavor/uk/forms.py
+++ b/django/contrib/localflavor/uk/forms.py
@@ -2,23 +2,39 @@
UK-specific Form helpers
"""
-from django.newforms.fields import RegexField, Select
+import re
+
+from django.newforms.fields import CharField, Select
+from django.newforms import ValidationError
from django.utils.translation import ugettext
-class UKPostcodeField(RegexField):
+class UKPostcodeField(CharField):
"""
A form field that validates its input is a UK postcode.
The regular expression used is sourced from the schema for British Standard
BS7666 address types: http://www.govtalk.gov.uk/gdsc/schemas/bs7666-v2-0.xsd
+
+ The value is uppercased and a space added in the correct place, if required.
"""
default_error_messages = {
- 'invalid': ugettext(u'Enter a postcode. A space is required between the two postcode parts.'),
+ 'invalid': ugettext(u'Enter a valid postcode.'),
}
+ outcode_pattern = '[A-PR-UWYZ]([0-9]{1,2}|([A-HIK-Y][0-9](|[0-9]|[ABEHMNPRVWXY]))|[0-9][A-HJKSTUW])'
+ incode_pattern = '[0-9][ABD-HJLNP-UW-Z]{2}'
+ postcode_regex = re.compile(r'^(GIR 0AA|%s %s)$' % (outcode_pattern, incode_pattern))
+ space_regex = re.compile(r' *(%s)$' % incode_pattern)
- def __init__(self, *args, **kwargs):
- super(UKPostcodeField, self).__init__(r'^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HIK-Y][0-9](|[0-9]|[ABEHMNPRVWXY]))|[0-9][A-HJKSTUW]) [0-9][ABD-HJLNP-UW-Z]{2})$',
- max_length=None, min_length=None, *args, **kwargs)
+ def clean(self, value):
+ value = super(UKPostcodeField, self).clean(value)
+ if value == u'':
+ return value
+ postcode = value.upper().strip()
+ # Put a single space before the incode (second part).
+ postcode = self.space_regex.sub(r' \1', postcode)
+ if not self.postcode_regex.search(postcode):
+ raise ValidationError(self.default_error_messages['invalid'])
+ return postcode
class UKCountySelect(Select):
"""