1 | """
|
---|
2 | Israeli-specific form helpers
|
---|
3 | """
|
---|
4 |
|
---|
5 | from django.forms import ValidationError
|
---|
6 | from django.forms.fields import RegexField, Field
|
---|
7 | from django.utils.translation import ugettext_lazy as _
|
---|
8 | import re
|
---|
9 |
|
---|
10 | id_number = re.compile(r'^(?P<number>\d{1,8})(?P<check>\d)$')
|
---|
11 |
|
---|
12 | class ILPostalCodeField(RegexField):
|
---|
13 | """
|
---|
14 | A form field that validates its input as an Israeli postal code.
|
---|
15 | Valid form is XXXXX where X represents integer.
|
---|
16 | """
|
---|
17 | default_error_messages = {
|
---|
18 | 'invalid': _(u'Enter a postal code in the format XXXXX'),
|
---|
19 | }
|
---|
20 |
|
---|
21 | def __init__(self, *args, **kwargs):
|
---|
22 | super(ILPostalCodeField, self).__init__(r'^\d{5}$',
|
---|
23 | max_length=None, min_length=None, *args, **kwargs)
|
---|
24 |
|
---|
25 | def clean(self, value):
|
---|
26 | """
|
---|
27 | Validates the input and returns a string that contains only numbers.
|
---|
28 | Returns an empty string for empty values.
|
---|
29 | """
|
---|
30 | return super(ILPostalCodeField, self).clean(value)
|
---|
31 |
|
---|
32 | class ILIDNumberField(Field):
|
---|
33 | """
|
---|
34 | Israeli identification number field.
|
---|
35 | """
|
---|
36 | default_error_messages = {
|
---|
37 | 'invalid': _(u'Enter a valid ID number.'),
|
---|
38 | }
|
---|
39 |
|
---|
40 | def clean(self, value):
|
---|
41 | super(ILIDNumberField, self).__init__(value)
|
---|
42 |
|
---|
43 | if value in EMPTY_VALUES:
|
---|
44 | return u''
|
---|
45 |
|
---|
46 | match = re.match(id_number, value)
|
---|
47 | if not match:
|
---|
48 | raise ValidationError(self.error_messages['invalid'])
|
---|
49 |
|
---|
50 | number, check = match.groupdict()['number'].zfill(8), int(match.groupdict()['check'])
|
---|
51 |
|
---|
52 | sum = 0
|
---|
53 | weight = 1
|
---|
54 | for digit in number+str(check):
|
---|
55 | sum += (lambda x: x/10 + x%10)(int(digit)*weight)
|
---|
56 | weight ^= 3
|
---|
57 |
|
---|
58 | if sum%10 != 0:
|
---|
59 | raise ValidationError(self.error_messages['invalid'])
|
---|
60 |
|
---|