2
South Africa-specific Form helpers
5
from django.forms import ValidationError
6
from django.forms.fields import Field, RegexField, EMPTY_VALUES
7
from django.utils.checksums import luhn
8
from django.utils.translation import gettext as _
10
from datetime import date
12
id_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
class ZAIDField(Field):
15
"""A form field for South African ID numbers -- the checksum is validated
16
using the Luhn checksum, and uses a simlistic (read: not entirely accurate)
17
check for the birthdate
19
default_error_messages = {
20
'invalid': _(u'Enter a valid South African ID number'),
23
def clean(self, value):
24
# strip spaces and dashes
25
value = value.strip().replace(' ', '').replace('-', '')
27
super(ZAIDField, self).clean(value)
29
if value in EMPTY_VALUES:
32
match = re.match(id_re, value)
35
raise ValidationError(self.error_messages['invalid'])
40
# The year 2000 is conveniently a leapyear.
41
# This algorithm will break in xx00 years which aren't leap years
42
# There is no way to guess the century of a ZA ID number
43
d = date(int(g['yy']) + 2000, int(g['mm']), int(g['dd']))
45
raise ValidationError(self.error_messages['invalid'])
48
raise ValidationError(self.error_messages['invalid'])
52
class ZAPostCodeField(RegexField):
53
default_error_messages = {
54
'invalid': _(u'Enter a valid South African postal code'),
57
def __init__(self, *args, **kwargs):
58
super(ZAPostCodeField, self).__init__(r'^\d{4}$',
59
max_length=None, min_length=None)