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