PageRenderTime 183ms CodeModel.GetById 101ms app.highlight 4ms RepoModel.GetById 76ms app.codeStats 0ms

/django/contrib/localflavor/za/forms.py

https://code.google.com/p/mango-py/
Python | 60 lines | 43 code | 9 blank | 8 comment | 4 complexity | 23ee2c920aa9688323f57ac8b8d63ea3 MD5 | raw file
 1"""
 2South Africa-specific Form helpers
 3"""
 4
 5from django.core.validators import EMPTY_VALUES
 6from django.forms import ValidationError
 7from django.forms.fields import Field, RegexField
 8from django.utils.checksums import luhn
 9from django.utils.translation import gettext as _
10import re
11from datetime import date
12
13id_re = re.compile(r'^(?P<yy>\d\d)(?P<mm>\d\d)(?P<dd>\d\d)(?P<mid>\d{4})(?P<end>\d{3})')
14
15class ZAIDField(Field):
16    """A form field for South African ID numbers -- the checksum is validated
17    using the Luhn checksum, and uses a simlistic (read: not entirely accurate)
18    check for the birthdate
19    """
20    default_error_messages = {
21        'invalid': _(u'Enter a valid South African ID number'),
22    }
23
24    def clean(self, value):
25        super(ZAIDField, self).clean(value)
26
27        if value in EMPTY_VALUES:
28            return u''
29
30        # strip spaces and dashes
31        value = value.strip().replace(' ', '').replace('-', '')
32
33        match = re.match(id_re, value)
34
35        if not match:
36            raise ValidationError(self.error_messages['invalid'])
37
38        g = match.groupdict()
39
40        try:
41            # The year 2000 is conveniently a leapyear.
42            # This algorithm will break in xx00 years which aren't leap years
43            # There is no way to guess the century of a ZA ID number
44            d = date(int(g['yy']) + 2000, int(g['mm']), int(g['dd']))
45        except ValueError:
46            raise ValidationError(self.error_messages['invalid'])
47
48        if not luhn(value):
49            raise ValidationError(self.error_messages['invalid'])
50
51        return value
52
53class ZAPostCodeField(RegexField):
54    default_error_messages = {
55        'invalid': _(u'Enter a valid South African postal code'),
56    }
57
58    def __init__(self, *args, **kwargs):
59        super(ZAPostCodeField, self).__init__(r'^\d{4}$',
60            max_length=None, min_length=None, *args, **kwargs)