Add Django-1.2.1
[frozenviper.git] / Django-1.2.1 / django / contrib / localflavor / fi / forms.py
blob9c163c91438c3aa183fbc4acb21dbc480821f19b
1 """
2 FI-specific Form helpers
3 """
5 import re
6 from django.core.validators import EMPTY_VALUES
7 from django.forms import ValidationError
8 from django.forms.fields import Field, RegexField, Select
9 from django.utils.translation import ugettext_lazy as _
11 class FIZipCodeField(RegexField):
12 default_error_messages = {
13 'invalid': _('Enter a zip code in the format XXXXX.'),
15 def __init__(self, *args, **kwargs):
16 super(FIZipCodeField, self).__init__(r'^\d{5}$',
17 max_length=None, min_length=None, *args, **kwargs)
19 class FIMunicipalitySelect(Select):
20 """
21 A Select widget that uses a list of Finnish municipalities as its choices.
22 """
23 def __init__(self, attrs=None):
24 from fi_municipalities import MUNICIPALITY_CHOICES
25 super(FIMunicipalitySelect, self).__init__(attrs, choices=MUNICIPALITY_CHOICES)
27 class FISocialSecurityNumber(Field):
28 default_error_messages = {
29 'invalid': _('Enter a valid Finnish social security number.'),
32 def clean(self, value):
33 super(FISocialSecurityNumber, self).clean(value)
34 if value in EMPTY_VALUES:
35 return u''
37 checkmarks = "0123456789ABCDEFHJKLMNPRSTUVWXY"
38 result = re.match(r"""^
39 (?P<date>([0-2]\d|3[01])
40 (0\d|1[012])
41 (\d{2}))
42 [A+-]
43 (?P<serial>(\d{3}))
44 (?P<checksum>[%s])$""" % checkmarks, value, re.VERBOSE | re.IGNORECASE)
45 if not result:
46 raise ValidationError(self.error_messages['invalid'])
47 gd = result.groupdict()
48 checksum = int(gd['date'] + gd['serial'])
49 if checkmarks[checksum % len(checkmarks)] == gd['checksum'].upper():
50 return u'%s' % value.upper()
51 raise ValidationError(self.error_messages['invalid'])