|
29
|
1 |
""" |
|
|
2 |
PT-specific Form helpers |
|
|
3 |
""" |
|
|
4 |
|
|
|
5 |
from django.core.validators import EMPTY_VALUES |
|
|
6 |
from django.forms import ValidationError |
|
|
7 |
from django.forms.fields import Field, RegexField, Select |
|
|
8 |
from django.utils.encoding import smart_unicode |
|
|
9 |
from django.utils.translation import ugettext_lazy as _ |
|
|
10 |
import re |
|
|
11 |
|
|
|
12 |
phone_digits_re = re.compile(r'^(\d{9}|(00|\+)\d*)$') |
|
|
13 |
|
|
|
14 |
|
|
|
15 |
class PTZipCodeField(RegexField): |
|
|
16 |
default_error_messages = { |
|
|
17 |
'invalid': _('Enter a zip code in the format XXXX-XXX.'), |
|
|
18 |
} |
|
|
19 |
|
|
|
20 |
def __init__(self, *args, **kwargs): |
|
|
21 |
super(PTZipCodeField, self).__init__(r'^(\d{4}-\d{3}|\d{7})$', |
|
|
22 |
max_length=None, min_length=None, *args, **kwargs) |
|
|
23 |
|
|
|
24 |
def clean(self,value): |
|
|
25 |
cleaned = super(PTZipCodeField, self).clean(value) |
|
|
26 |
if len(cleaned) == 7: |
|
|
27 |
return u'%s-%s' % (cleaned[:4],cleaned[4:]) |
|
|
28 |
else: |
|
|
29 |
return cleaned |
|
|
30 |
|
|
|
31 |
class PTPhoneNumberField(Field): |
|
|
32 |
""" |
|
|
33 |
Validate local Portuguese phone number (including international ones) |
|
|
34 |
It should have 9 digits (may include spaces) or start by 00 or + (international) |
|
|
35 |
""" |
|
|
36 |
default_error_messages = { |
|
|
37 |
'invalid': _('Phone numbers must have 9 digits, or start by + or 00.'), |
|
|
38 |
} |
|
|
39 |
|
|
|
40 |
def clean(self, value): |
|
|
41 |
super(PTPhoneNumberField, 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' % value |
|
|
48 |
raise ValidationError(self.error_messages['invalid']) |