| | 1 | # -*- coding: iso-8859-1 -*- |
| | 2 | """ |
| | 3 | NO-specific Form helpers |
| | 4 | """ |
| | 5 | |
| | 6 | import re, datetime |
| | 7 | from django.newforms import ValidationError |
| | 8 | from django.newforms.fields import Field, RegexField, Select, EMPTY_VALUES |
| | 9 | from django.utils.translation import gettext |
| | 10 | |
| | 11 | class NOZipCodeField(RegexField): |
| | 12 | def __init__(self, *args, **kwargs): |
| | 13 | super(NOZipCodeField, self).__init__(r'^\d{4}$', |
| | 14 | max_length=None, min_length=None, |
| | 15 | error_message=gettext(u'Enter a zip code in the format XXXX.'), |
| | 16 | *args, **kwargs) |
| | 17 | |
| | 18 | class NOMunicipalitySelect(Select): |
| | 19 | """ |
| | 20 | A Select widget that uses a list of Norwegian municipalities (fylker) |
| | 21 | as its choices. |
| | 22 | """ |
| | 23 | def __init__(self, attrs=None): |
| | 24 | from no_municipalities import MUNICIPALITY_CHOICES # relative import |
| | 25 | super(NOMunicipalitySelect, self).__init__(attrs, choices=MUNICIPALITY_CHOICES) |
| | 26 | |
| | 27 | class NOSocialSecurityNumber(Field): |
| | 28 | """ |
| | 29 | Algorithm is documented at http://no.wikipedia.org/wiki/Personnummer |
| | 30 | """ |
| | 31 | def clean(self, value): |
| | 32 | super(NOSocialSecurityNumber, self).clean(value) |
| | 33 | if value in EMPTY_VALUES: |
| | 34 | return u'' |
| | 35 | |
| | 36 | msg = gettext(u'Enter a valid Norwegian social security number.') |
| | 37 | if not re.match(r'^\d{11}$', value): |
| | 38 | raise ValidationError(msg) |
| | 39 | |
| | 40 | day = int(value[:2]) |
| | 41 | month = int(value[2:4]) |
| | 42 | year2 = int(value[4:6]) |
| | 43 | |
| | 44 | inum = int(value[6:9]) |
| | 45 | self.birthday = None |
| | 46 | try: |
| | 47 | if 000 <= inum < 500: |
| | 48 | self.birthday = datetime.date(1900+year2, month, day) |
| | 49 | if 500 <= inum < 750: |
| | 50 | self.birthday = datetime.date(1800+year2, month, day) |
| | 51 | if 500 <= inum < 1000: |
| | 52 | self.birthday = datetime.date(2000+year2, month, day) |
| | 53 | except ValueError: |
| | 54 | raise ValidationError(msg) |
| | 55 | |
| | 56 | sexnum = int(value[8]) |
| | 57 | if sexnum % 2 == 0: |
| | 58 | self.gender = 'F' |
| | 59 | else: |
| | 60 | self.gender = 'M' |
| | 61 | |
| | 62 | digits = map(int, list(value)) |
| | 63 | weight_1 = [3, 7, 6, 1, 8, 9, 4, 5, 2, 1, 0] |
| | 64 | weight_2 = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2, 1] |
| | 65 | |
| | 66 | def multiply_reduce(aval, bval): |
| | 67 | return sum((a * b) for (a, b) in zip(aval, bval)) |
| | 68 | |
| | 69 | if multiply_reduce(digits, weight_1) % 11 != 0: |
| | 70 | raise ValidationError(msg) |
| | 71 | if multiply_reduce(digits, weight_2) % 11 != 0: |
| | 72 | raise ValidationError(msg) |
| | 73 | |
| | 74 | return value |
| | 75 | |