PageRenderTime 92ms CodeModel.GetById 88ms app.highlight 2ms RepoModel.GetById 1ms app.codeStats 0ms

/django/contrib/localflavor/pt/forms.py

https://code.google.com/p/mango-py/
Python | 48 lines | 33 code | 8 blank | 7 comment | 3 complexity | 498e42855e7d6cc73e78d923eabccb25 MD5 | raw file
 1"""
 2PT-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
 8from django.utils.encoding import smart_unicode
 9from django.utils.translation import ugettext_lazy as _
10import re
11
12phone_digits_re = re.compile(r'^(\d{9}|(00|\+)\d*)$')
13
14
15class 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        
31class 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'])