1 # -*- coding: utf-8 -*-
3 Spanish-specific Form helpers
6 from __future__
import absolute_import
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
):
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.
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
):
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
43 TODO: accept and strip characters like dot, hyphen... in phone number
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
):
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.
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'
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 '')],
91 def clean(self
, value
):
92 super(ESIdentityCardNumberField
, self
).clean(value
)
93 if value
in EMPTY_VALUES
:
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
:
103 if letter2
== nif_get_checksum(number
):
106 raise ValidationError(self
.error_messages
['invalid_nif'])
107 elif letter1
in self
.nie_types
and letter2
:
109 if letter2
== nif_get_checksum(number
):
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]:
116 number
, letter2
= number
[:-1], int(number
[-1])
117 checksum
= cif_get_checksum(number
)
118 if letter2
in (checksum
, self
.cif_control
[checksum
]):
121 raise ValidationError(self
.error_messages
['invalid_cif'])
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:
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
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
:
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
:
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