2 FI-specific Form helpers
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
):
21 A Select widget that uses a list of Finnish municipalities as its choices.
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
:
37 checkmarks
= "0123456789ABCDEFHJKLMNPRSTUVWXY"
38 result
= re
.match(r
"""^
39 (?P<date>([0-2]\d|3[01])
44 (?P<checksum>[%s])$""" % checkmarks
, value
, re
.VERBOSE | re
.IGNORECASE
)
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'])