Ticket #3908: localflavor_br.diff

File localflavor_br.diff, 2.4 KB (added by danielvaz@…, 18 years ago)

BRCPFField added.

  • django/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    """
     45    A field with validate CPF.
     46    """
     47    def __init__(self, *args, **kwargs):
     48        super(BRCPFField, self).__init__(max_length=11, *args, **kwargs)
     49
     50    def clean(self, value):
     51        super(BRCPFField, self).clean(value)
     52        if value in EMPTY_VALUES:
     53            return u''
     54        try:
     55            int(value)
     56        except ValueError:
     57             raise ValidationError(gettext(u'The CPF field must contain only \
     58numbers.'))
     59        if self.__validate_cpf__(value):
     60            return value
     61
     62    def __validate_cpf__(self, cpf):
     63        if len(cpf) < 11:
     64            raise ValidationError(gettext(u'Invalid CPF. The CPF field must \
     65contain 11 digits.'))
     66        number = 0
     67        for i,j in enumerate(range(10,1,-1)):
     68            number += int(cpf[i])*j
     69        if self.__create_dv__(number) <> cpf[9]:
     70            raise ValidationError(gettext(u'Invalid CPF.'))
     71
     72        number = 0
     73       
     74        for i,j in enumerate(range(11,1,-1)):
     75            number += int(cpf[i])*j
     76        if self.__create_dv__(number) <> cpf[10]:
     77            raise ValidationError(gettext(u'Invalid CPF.'))
     78        return True
     79
     80    def __create_dv__(self, number):
     81        if number % 11 > 1:
     82            return str(11 - number % 11)
     83        else:
     84            return '0'
Back to Top