Ticket #3930: brcpffield_add.diff

File brcpffield_add.diff, 2.3 KB (added by anonymous, 18 years ago)
  • contrib/localflavor/br/forms.py

     
    55
    66from django.newforms import ValidationError
    77from django.newforms.fields import Field, RegexField, Select, EMPTY_VALUES
     8from django.newforms.fields import CharField
    89from django.newforms.util import smart_unicode
    910from django.utils.translation import gettext
    1011import re
     
    2728        m = phone_digits_re.search(value)
    2829        if m:
    2930            return u'%s-%s-%s' % (m.group(1), m.group(2), m.group(3))
    30         raise ValidationError(gettext(u'Phone numbers must be in XX-XXXX-XXXX format.'))
     31        raise ValidationError(gettext(u'Phone numbers must be in XX-XXXX-XXXX
     32format.'))
    3133
    3234class BRStateSelect(Select):
    3335    """
     
    3739    def __init__(self, attrs=None):
    3840        from br_states import STATE_CHOICES # relative import
    3941        super(BRStateSelect, self).__init__(attrs, choices=STATE_CHOICES)
     42       
     43class BRCPFField(CharField):
     44    def __init__(self, *args, **kwargs):
     45        super(BRCPFField, self).__init__(max_length=11, *args, **kwargs)
     46
     47    def clean(self, value):
     48        super(BRCPFField, self).clean(value)
     49        if value in EMPTY_VALUES:
     50            return u''
     51        try:
     52            int(value)
     53        except ValueError:
     54             raise ValidationError(gettext(u'The CPF field must contain only
     55numbers.'))
     56        if self._validate_cpf(value):
     57            return value
     58
     59    def _validate_cpf(self, cpf):
     60        if len(cpf) < 11:
     61            raise ValidationError(gettext(u'Invalid CPF. The CPF field must
     62contain 11 digits.'))
     63        number = 0
     64        for i,j in enumerate(range(10,1,-1)):
     65            number += int(cpf[i])*j
     66        if self._create_dv(number) <> cpf[9]:
     67            raise ValidationError(gettext(u'Invalid CPF.'))
     68
     69        number = 0
     70       
     71        for i,j in enumerate(range(11,1,-1)):
     72            number += int(cpf[i])*j
     73        if self._create_dv(number) <> cpf[10]:
     74            raise ValidationError(gettext(u'Invalid CPF.'))
     75        return True
     76
     77    def _create_dv(self, number):
     78        if number % 11 > 1:
     79            return str(11 - number % 11)
     80        else:
     81            return '0'
Back to Top