PageRenderTime 83ms CodeModel.GetById 40ms app.highlight 10ms RepoModel.GetById 31ms app.codeStats 0ms

/django/contrib/localflavor/tr/forms.py

https://code.google.com/p/mango-py/
Python | 91 lines | 83 code | 5 blank | 3 comment | 3 complexity | da5b653cf174a14f513b18c675d63c19 MD5 | raw file
 1"""
 2TR-specific Form helpers
 3"""
 4
 5from django.core.validators import EMPTY_VALUES
 6from django.forms import ValidationError
 7from django.forms.fields import Field, RegexField, Select, CharField
 8from django.utils.encoding import smart_unicode
 9from django.utils.translation import ugettext_lazy as _
10import re
11
12phone_digits_re = re.compile(r'^(\+90|0)? ?(([1-9]\d{2})|\([1-9]\d{2}\)) ?([2-9]\d{2} ?\d{2} ?\d{2})$')
13
14class TRPostalCodeField(RegexField):
15    default_error_messages = {
16        'invalid': _(u'Enter a postal code in the format XXXXX.'),
17    }
18
19    def __init__(self, *args, **kwargs):
20        super(TRPostalCodeField, self).__init__(r'^\d{5}$',
21            max_length=5, min_length=5, *args, **kwargs)
22
23    def clean(self, value):
24        value = super(TRPostalCodeField, self).clean(value)
25        if value in EMPTY_VALUES:
26            return u''
27        if len(value) != 5:
28            raise ValidationError(self.error_messages['invalid'])
29        province_code = int(value[:2])
30        if province_code == 0 or province_code > 81:
31            raise ValidationError(self.error_messages['invalid'])
32        return value
33
34
35class TRPhoneNumberField(CharField):
36    default_error_messages = {
37        'invalid': _(u'Phone numbers must be in 0XXX XXX XXXX format.'),
38    }
39
40    def clean(self, value):
41        super(TRPhoneNumberField, self).clean(value)
42        if value in EMPTY_VALUES:
43            return u''
44        value = re.sub('(\(|\)|\s+)', '', smart_unicode(value))
45        m = phone_digits_re.search(value)
46        if m:
47            return u'%s%s' % (m.group(2), m.group(4))
48        raise ValidationError(self.error_messages['invalid'])
49
50class TRIdentificationNumberField(Field):
51    """
52    A Turkey Identification Number number.
53    See: http://tr.wikipedia.org/wiki/T%C3%BCrkiye_Cumhuriyeti_Kimlik_Numaras%C4%B1
54
55    Checks the following rules to determine whether the number is valid:
56
57        * The number is 11-digits.
58        * First digit is not 0.
59        * Conforms to the following two formula:
60          (sum(1st, 3rd, 5th, 7th, 9th)*7 - sum(2nd,4th,6th,8th)) % 10 = 10th digit
61          sum(1st to 10th) % 10 = 11th digit
62    """
63    default_error_messages = {
64        'invalid': _(u'Enter a valid Turkish Identification number.'),
65        'not_11': _(u'Turkish Identification number must be 11 digits.'),
66    }
67
68    def clean(self, value):
69        super(TRIdentificationNumberField, self).clean(value)
70        if value in EMPTY_VALUES:
71            return u''
72        if len(value) != 11:
73            raise ValidationError(self.error_messages['not_11'])
74        if not re.match(r'^\d{11}$', value):
75            raise ValidationError(self.error_messages['invalid'])
76        if int(value[0]) == 0:
77            raise ValidationError(self.error_messages['invalid'])
78        chksum = (sum([int(value[i]) for i in xrange(0,9,2)])*7-
79                          sum([int(value[i]) for i in xrange(1,9,2)])) % 10
80        if chksum != int(value[9]) or \
81           (sum([int(value[i]) for i in xrange(10)]) % 10) != int(value[10]):
82            raise ValidationError(self.error_messages['invalid'])
83        return value
84
85class TRProvinceSelect(Select):
86    """
87    A Select widget that uses a list of provinces in Turkey as its choices.
88    """
89    def __init__(self, attrs=None):
90        from tr_provinces import PROVINCE_CHOICES
91        super(TRProvinceSelect, self).__init__(attrs, choices=PROVINCE_CHOICES)