PageRenderTime 23ms CodeModel.GetById 14ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 1ms

/django/contrib/localflavor/at/forms.py

https://code.google.com/p/mango-py/
Python | 69 lines | 48 code | 8 blank | 13 comment | 2 complexity | f07c9d82b2753e487ef4e396180183a8 MD5 | raw file
 1"""
 2AT-specific Form helpers
 3"""
 4
 5import re
 6
 7from django.core.validators import EMPTY_VALUES
 8from django.forms import ValidationError
 9from django.forms.fields import Field, RegexField, Select
10from django.utils.translation import ugettext_lazy as _
11
12re_ssn = re.compile(r'^\d{4} \d{6}')
13
14
15class ATZipCodeField(RegexField):
16    """
17    A form field that validates its input is an Austrian postcode.
18
19    Accepts 4 digits.
20    """
21    default_error_messages = {
22        'invalid': _('Enter a zip code in the format XXXX.'),
23    }
24    def __init__(self, *args, **kwargs):
25        super(ATZipCodeField, self).__init__(r'^\d{4}$',
26                max_length=None, min_length=None, *args, **kwargs)
27
28class ATStateSelect(Select):
29    """
30    A Select widget that uses a list of AT states as its choices.
31    """
32    def __init__(self, attrs=None):
33        from django.contrib.localflavor.at.at_states import STATE_CHOICES
34        super(ATStateSelect, self).__init__(attrs, choices=STATE_CHOICES)
35
36class ATSocialSecurityNumberField(Field):
37    """
38    Austrian Social Security numbers are composed of a 4 digits and 6 digits
39    field. The latter represents in most cases the person's birthdate while
40    the first 4 digits represent a 3-digits counter and a one-digit checksum.
41
42    The 6-digits field can also differ from the person's birthdate if the
43    3-digits counter suffered an overflow.
44
45    This code is based on information available on
46    http://de.wikipedia.org/wiki/Sozialversicherungsnummer#.C3.96sterreich
47    """
48
49    default_error_messages = {
50        'invalid': _(u'Enter a valid Austrian Social Security Number in XXXX XXXXXX format.'),
51    }
52
53    def clean(self, value):
54        value = super(ATSocialSecurityNumberField, self).clean(value)
55        if value in EMPTY_VALUES:
56            return u""
57        if not re_ssn.search(value):
58            raise ValidationError(self.error_messages['invalid'])
59        sqnr, date = value.split(" ")
60        sqnr, check = (sqnr[:3], (sqnr[3]))
61        if int(sqnr) < 100:
62           raise ValidationError(self.error_messages['invalid'])
63        res = int(sqnr[0])*3 + int(sqnr[1])*7 + int(sqnr[2])*9 \
64           + int(date[0])*5 + int(date[1])*8 + int(date[2])*4 \
65           + int(date[3])*2 + int(date[4])*1 + int(date[5])*6
66        res = res % 11
67        if res != int(check):
68           raise ValidationError(self.error_messages['invalid'])
69        return u'%s%s %s'%(sqnr, check, date,)