App Engine Python SDK version 1.7.4 (2)
[gae.git] / python / lib / django_1_4 / django / contrib / localflavor / es / forms.py
blobfe237270f529258db36e7a3c5f5c5ac0e2ccd205
1 # -*- coding: utf-8 -*-
2 """
3 Spanish-specific Form helpers
4 """
6 from __future__ import absolute_import
8 import re
10 from django.contrib.localflavor.es.es_provinces import PROVINCE_CHOICES
11 from django.contrib.localflavor.es.es_regions import REGION_CHOICES
12 from django.core.validators import EMPTY_VALUES
13 from django.forms import ValidationError
14 from django.forms.fields import RegexField, Select
15 from django.utils.translation import ugettext_lazy as _
18 class ESPostalCodeField(RegexField):
19 """
20 A form field that validates its input as a spanish postal code.
22 Spanish postal code is a five digits string, with two first digits
23 between 01 and 52, assigned to provinces code.
24 """
25 default_error_messages = {
26 'invalid': _('Enter a valid postal code in the range and format 01XXX - 52XXX.'),
29 def __init__(self, max_length=None, min_length=None, *args, **kwargs):
30 super(ESPostalCodeField, self).__init__(
31 r'^(0[1-9]|[1-4][0-9]|5[0-2])\d{3}$',
32 max_length, min_length, *args, **kwargs)
34 class ESPhoneNumberField(RegexField):
35 """
36 A form field that validates its input as a Spanish phone number.
37 Information numbers are ommited.
39 Spanish phone numbers are nine digit numbers, where first digit is 6 (for
40 cell phones), 8 (for special phones), or 9 (for landlines and special
41 phones)
43 TODO: accept and strip characters like dot, hyphen... in phone number
44 """
45 default_error_messages = {
46 'invalid': _('Enter a valid phone number in one of the formats 6XXXXXXXX, 8XXXXXXXX or 9XXXXXXXX.'),
49 def __init__(self, max_length=None, min_length=None, *args, **kwargs):
50 super(ESPhoneNumberField, self).__init__(r'^(6|7|8|9)\d{8}$',
51 max_length, min_length, *args, **kwargs)
53 class ESIdentityCardNumberField(RegexField):
54 """
55 Spanish NIF/NIE/CIF (Fiscal Identification Number) code.
57 Validates three diferent formats:
59 NIF (individuals): 12345678A
60 CIF (companies): A12345678
61 NIE (foreigners): X12345678A
63 according to a couple of simple checksum algorithms.
65 Value can include a space or hyphen separator between number and letters.
66 Number length is not checked for NIF (or NIE), old values start with a 1,
67 and future values can contain digits greater than 8. The CIF control digit
68 can be a number or a letter depending on company type. Algorithm is not
69 public, and different authors have different opinions on which ones allows
70 letters, so both validations are assumed true for all types.
71 """
72 default_error_messages = {
73 'invalid': _('Please enter a valid NIF, NIE, or CIF.'),
74 'invalid_only_nif': _('Please enter a valid NIF or NIE.'),
75 'invalid_nif': _('Invalid checksum for NIF.'),
76 'invalid_nie': _('Invalid checksum for NIE.'),
77 'invalid_cif': _('Invalid checksum for CIF.'),
80 def __init__(self, only_nif=False, max_length=None, min_length=None, *args, **kwargs):
81 self.only_nif = only_nif
82 self.nif_control = 'TRWAGMYFPDXBNJZSQVHLCKE'
83 self.cif_control = 'JABCDEFGHI'
84 self.cif_types = 'ABCDEFGHKLMNPQS'
85 self.nie_types = 'XT'
86 id_card_re = re.compile(r'^([%s]?)[ -]?(\d+)[ -]?([%s]?)$' % (self.cif_types + self.nie_types, self.nif_control + self.cif_control), re.IGNORECASE)
87 super(ESIdentityCardNumberField, self).__init__(id_card_re, max_length, min_length,
88 error_message=self.default_error_messages['invalid%s' % (self.only_nif and '_only_nif' or '')],
89 *args, **kwargs)
91 def clean(self, value):
92 super(ESIdentityCardNumberField, self).clean(value)
93 if value in EMPTY_VALUES:
94 return u''
95 nif_get_checksum = lambda d: self.nif_control[int(d)%23]
97 value = value.upper().replace(' ', '').replace('-', '')
98 m = re.match(r'^([%s]?)[ -]?(\d+)[ -]?([%s]?)$' % (self.cif_types + self.nie_types, self.nif_control + self.cif_control), value)
99 letter1, number, letter2 = m.groups()
101 if not letter1 and letter2:
102 # NIF
103 if letter2 == nif_get_checksum(number):
104 return value
105 else:
106 raise ValidationError(self.error_messages['invalid_nif'])
107 elif letter1 in self.nie_types and letter2:
108 # NIE
109 if letter2 == nif_get_checksum(number):
110 return value
111 else:
112 raise ValidationError(self.error_messages['invalid_nie'])
113 elif not self.only_nif and letter1 in self.cif_types and len(number) in [7, 8]:
114 # CIF
115 if not letter2:
116 number, letter2 = number[:-1], int(number[-1])
117 checksum = cif_get_checksum(number)
118 if letter2 in (checksum, self.cif_control[checksum]):
119 return value
120 else:
121 raise ValidationError(self.error_messages['invalid_cif'])
122 else:
123 raise ValidationError(self.error_messages['invalid'])
125 class ESCCCField(RegexField):
127 A form field that validates its input as a Spanish bank account or CCC
128 (Codigo Cuenta Cliente).
130 Spanish CCC is in format EEEE-OOOO-CC-AAAAAAAAAA where:
132 E = entity
133 O = office
134 C = checksum
135 A = account
137 It's also valid to use a space as delimiter, or to use no delimiter.
139 First checksum digit validates entity and office, and last one
140 validates account. Validation is done multiplying every digit of 10
141 digit value (with leading 0 if necessary) by number in its position in
142 string 1, 2, 4, 8, 5, 10, 9, 7, 3, 6. Sum resulting numbers and extract
143 it from 11. Result is checksum except when 10 then is 1, or when 11
144 then is 0.
146 TODO: allow IBAN validation too
148 default_error_messages = {
149 'invalid': _('Please enter a valid bank account number in format XXXX-XXXX-XX-XXXXXXXXXX.'),
150 'checksum': _('Invalid checksum for bank account number.'),
153 def __init__(self, max_length=None, min_length=None, *args, **kwargs):
154 super(ESCCCField, self).__init__(r'^\d{4}[ -]?\d{4}[ -]?\d{2}[ -]?\d{10}$',
155 max_length, min_length, *args, **kwargs)
157 def clean(self, value):
158 super(ESCCCField, self).clean(value)
159 if value in EMPTY_VALUES:
160 return u''
161 control_str = [1, 2, 4, 8, 5, 10, 9, 7, 3, 6]
162 m = re.match(r'^(\d{4})[ -]?(\d{4})[ -]?(\d{2})[ -]?(\d{10})$', value)
163 entity, office, checksum, account = m.groups()
164 get_checksum = lambda d: str(11 - sum([int(digit) * int(control) for digit, control in zip(d, control_str)]) % 11).replace('10', '1').replace('11', '0')
165 if get_checksum('00' + entity + office) + get_checksum(account) == checksum:
166 return value
167 else:
168 raise ValidationError(self.error_messages['checksum'])
170 class ESRegionSelect(Select):
172 A Select widget that uses a list of spanish regions as its choices.
174 def __init__(self, attrs=None):
175 super(ESRegionSelect, self).__init__(attrs, choices=REGION_CHOICES)
177 class ESProvinceSelect(Select):
179 A Select widget that uses a list of spanish provinces as its choices.
181 def __init__(self, attrs=None):
182 super(ESProvinceSelect, self).__init__(attrs, choices=PROVINCE_CHOICES)
185 def cif_get_checksum(number):
186 s1 = sum([int(digit) for pos, digit in enumerate(number) if int(pos) % 2])
187 s2 = sum([sum([int(unit) for unit in str(int(digit) * 2)]) for pos, digit in enumerate(number) if not int(pos) % 2])
188 return (10 - ((s1 + s2) % 10)) % 10