|
0
|
1 |
""" |
|
|
2 |
FI-specific Form helpers |
|
|
3 |
""" |
|
|
4 |
|
|
|
5 |
import re |
|
29
|
6 |
from django.core.validators import EMPTY_VALUES |
|
0
|
7 |
from django.forms import ValidationError |
|
29
|
8 |
from django.forms.fields import Field, RegexField, Select |
|
0
|
9 |
from django.utils.translation import ugettext_lazy as _ |
|
|
10 |
|
|
|
11 |
class FIZipCodeField(RegexField): |
|
|
12 |
default_error_messages = { |
|
|
13 |
'invalid': _('Enter a zip code in the format XXXXX.'), |
|
|
14 |
} |
|
|
15 |
def __init__(self, *args, **kwargs): |
|
|
16 |
super(FIZipCodeField, self).__init__(r'^\d{5}$', |
|
|
17 |
max_length=None, min_length=None, *args, **kwargs) |
|
|
18 |
|
|
|
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) |
|
|
26 |
|
|
|
27 |
class FISocialSecurityNumber(Field): |
|
|
28 |
default_error_messages = { |
|
|
29 |
'invalid': _('Enter a valid Finnish social security number.'), |
|
|
30 |
} |
|
|
31 |
|
|
|
32 |
def clean(self, value): |
|
|
33 |
super(FISocialSecurityNumber, self).clean(value) |
|
|
34 |
if value in EMPTY_VALUES: |
|
|
35 |
return u'' |
|
|
36 |
|
|
|
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']) |