Ticket #3919: idcardnumber.diff

File idcardnumber.diff, 4.6 KB (added by Jannis Leidel <jl@…>, 18 years ago)

initial idcardnumber field

  • django/contrib/localflavor/de/forms.py

     
    77from django.utils.translation import gettext
    88import re
    99
     10id_re = re.compile(r"^(?P<residence>\d{10})(?P<origin>\w{1,3})[-\ ]?(?P<birthday>\d{7})[-\ ]?(?P<validity>\d{7})[-\ ]?(?P<checksum>\d{1})$")
     11
    1012class DEZipCodeField(RegexField):
    1113    def __init__(self, *args, **kwargs):
    1214        super(DEZipCodeField, self).__init__(r'^\d{5}$',
     
    2123    def __init__(self, attrs=None):
    2224        from de_states import STATE_CHOICES # relative import
    2325        super(DEStateSelect, self).__init__(attrs, choices=STATE_CHOICES)
     26
     27class DEIdentityCardNumberField(Field):
     28    """
     29    A German identity card number.
     30
     31    Checks the following rules to determine whether the number is valid:
     32
     33        * Conforms to the XXXXXXXXXXX-XXXXXXX-XXXXXXX-X format.
     34        * No group consists entirely of zeroes.
     35        * Included checksums match calculated checksums
     36
     37    Algorithm is documented at http://de.wikipedia.org/wiki/Personalausweis
     38    """
     39    def has_valid_checksum(self, number):
     40        given_number, given_checksum = number[:-1], number[-1]
     41        calculated_checksum = 0
     42        fragment = ""
     43        parameter = 7
     44
     45        for i in range(len(given_number)):
     46          fragment = str(int(given_number[i])*parameter)
     47          if fragment.isalnum():
     48            calculated_checksum += int(fragment[-1])
     49
     50          if parameter == 1:
     51            parameter = 7
     52          elif parameter == 3:
     53            parameter = 1
     54          elif parameter ==7:
     55            parameter = 3
     56
     57        if str(calculated_checksum)[-1] == given_checksum:
     58            return True
     59        return False
     60
     61    def clean(self, value):
     62        super(DEIdentityCardNumberField, self).clean(value)
     63        error_msg = gettext(u'Enter a valid German identity card number in XXXXXXXXXXX-XXXXXXX-XXXXXXX-X format')
     64        if value in EMPTY_VALUES:
     65            return u''
     66        match = re.match(id_re, value)
     67        if not match:
     68            raise ValidationError(error_msg)
     69
     70        residence, origin, birthday, validity, checksum = \
     71        match.groupdict()['residence'], match.groupdict()['origin'], \
     72        match.groupdict()['birthday'], match.groupdict()['validity'], \
     73        match.groupdict()['checksum']
     74
     75        if residence == '0000000000' or \
     76           birthday == '0000000' or \
     77           validity == '0000000':
     78            raise ValidationError(error_msg)
     79
     80        all_digits = "%s%s%s%s" % (residence, birthday, validity, checksum)
     81        if not self.has_valid_checksum(residence) or \
     82            not self.has_valid_checksum(birthday) or \
     83            not self.has_valid_checksum(validity) or \
     84            not self.has_valid_checksum(all_digits):
     85                raise ValidationError(error_msg)
     86
     87        return u'%s%s-%s-%s-%s' % (residence, origin, birthday, validity, checksum)
  • tests/regressiontests/forms/localflavor.py

     
    870870>>> w.render('states', 'TH')
    871871u'<select name="states">\n<option value="BW">Baden-W\xfcrttemberg</option>\n<option value="BY">Bavaria</option>\n<option value="BE">Berlin</option>\n<option value="BB">Brandenburg</option>\n<option value="HB">Bremen</option>\n<option value="HH">Hamburg</option>\n<option value="HE">Hessen</option>\n<option value="MV">Mecklenburg-Western Pomerania</option>\n<option value="NI">Lower Saxony</option>\n<option value="NW">North Rhine-Westphalia</option>\n<option value="RP">Rhineland-Palatinate</option>\n<option value="SL">Saarland</option>\n<option value="SN">Saxony</option>\n<option value="ST">Saxony-Anhalt</option>\n<option value="SH">Schleswig-Holstein</option>\n<option value="TH" selected="selected">Thuringia</option>\n</select>'
    872872"""
     873
     874# DEIdentityCardNumberField #################################################
     875
     876>>> from django.contrib.localflavor.de.forms import DEIdentityCardNumberField
     877>>> f = DEIdentityCardNumberField()
     878>>> f.clean('7549313035D-6004103-0903042-0')
     879u'7549313035D-6004103-0903042-0'
     880>>> f.clean('9786324830D 6104243 0910271 2')
     881u'9786324830D-6104243-0910271-2'
     882>>> f.clean('0434657485D-6407276-0508137-9')
     883Traceback (most recent call last):
     884...
     885ValidationError: [u'Enter a valid German identity card number in XXXXXXXXXXX-XXXXXXX-XXXXXXX-X format']
Back to Top