Ticket #10895: localflavor_br_forms_r10620_updated.diff

File localflavor_br_forms_r10620_updated.diff, 7.4 KB (added by luizvital, 16 years ago)

Patch updated with ramalho's advices

  • django/contrib/localflavor/br/forms.py

     
    8686    """
    8787    This field validate a CPF number or a CPF string. A CPF number is
    8888    compounded by XXX.XXX.XXX-VD. The two last digits are check digits.
     89    By default, the cleaned value is in the same format as entered.
     90    If you'd like to keep a unique format for cleaned values use
     91    the parameter "return_format" to provide the string format of the cleaned
     92    value.
     93   
     94    You can use one of these class constants to the "return_format" parameter:
     95   
     96      DIGITS_ONLY = '%s%s%s%s' (ex. XXXXXXXXXXVD)
     97      DOTS_AND_DASH = '%s.%s.%s-%s' (ex. XXX.XXX.XXX-VD)
    8998
    9099    More information:
    91100    http://en.wikipedia.org/wiki/Cadastro_de_Pessoas_F%C3%ADsicas
     
    96105        'digits_only': _("This field requires only numbers."),
    97106    }
    98107
    99     def __init__(self, *args, **kwargs):
    100         super(BRCPFField, self).__init__(max_length=14, min_length=11, *args, **kwargs)
     108    DIGITS_ONLY = u'%s%s%s%s'
     109    DOTS_AND_DASH = u'%s.%s.%s-%s'
    101110
     111    def __init__(self, return_format=None, *args, **kwargs):
     112        self.return_format = return_format
     113        super(BRCPFField, self).__init__(max_length=14, min_length=11,
     114                                         *args, **kwargs)
     115
    102116    def clean(self, value):
    103117        """
    104118        Value can be either a string in the format XXX.XXX.XXX-XX or an
     
    116130            raise ValidationError(self.error_messages['digits_only'])
    117131        if len(value) != 11:
    118132            raise ValidationError(self.error_messages['max_digits'])
     133
     134        # exclude cases of repeated digits form 0 to 9
     135        if value in [str(d) * 11 for d in range(10)]:
     136            raise ValidationError(self.error_messages['invalid'])
     137
    119138        orig_dv = value[-2:]
    120 
    121139        new_1dv = sum([i * int(value[idx]) for idx, i in enumerate(range(10, 1, -1))])
    122140        new_1dv = DV_maker(new_1dv % 11)
    123141        value = value[:-2] + str(new_1dv) + value[-1]
     
    127145        if value[-2:] != orig_dv:
    128146            raise ValidationError(self.error_messages['invalid'])
    129147
     148        # return a formatted string if asked
     149        if self.return_format:
     150            value = re.sub(r'[-\.]', '', orig_value)
     151            return self.return_format % tuple(re.findall(r'(\d{2,3})', value))
     152
    130153        return orig_value
    131154
    132 class BRCNPJField(Field):
     155class BRCNPJField(CharField):
     156    """
     157    This field validates a CNPJ number or a CNPJ string. A CNPJ number is
     158    compounded by XX.XXX.XXX/XXXX-XX.
     159    By default, the cleaned value is in the same format as entered.
     160    If you'd like to keep a unique format for cleaned values use
     161    the parameter "return_format" to provide the string format of the cleaned
     162    value.
     163   
     164    You can use one of these class constants to the "return_format" parameter:
     165   
     166      DIGITS_ONLY = '%s%s%s%s%s' (ex. XXXXXXXXXXXXXX)
     167      DOTS_SLASH_DASH = '%s.%s.%s/%s-%s' (ex. XX.XXX.XXX/XXXX-XX)
     168   
     169    """
    133170    default_error_messages = {
    134171        'invalid': _("Invalid CNPJ number."),
    135172        'digits_only': _("This field requires only numbers."),
    136173        'max_digits': _("This field requires at least 14 digits"),
    137174    }
    138175
     176    DIGITS_ONLY = u'%s%s%s%s%s'
     177    DOTS_SLASH_DASH = u'%s.%s.%s/%s-%s'
     178   
     179    def __init__(self, return_format=None, *args, **kwargs):
     180        self.return_format = return_format
     181        super(BRCNPJField, self).__init__(max_length=18, min_length=14,
     182                                          *args, **kwargs)   
     183
    139184    def clean(self, value):
    140185        """
    141186        Value can be either a string in the format XX.XXX.XXX/XXXX-XX or a
     
    163208        value = value[:-1] + str(new_2dv)
    164209        if value[-2:] != orig_dv:
    165210            raise ValidationError(self.error_messages['invalid'])
     211           
     212        if self.return_format:
     213            value = re.sub('[-/\.]', '', orig_value)
     214            m = re.match(r'(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})', value)
     215            return self.return_format % tuple(m.groups())
    166216
    167217        return orig_value
  • tests/regressiontests/forms/localflavor/br.py

     
    8585...
    8686ValidationError: [u'Invalid CNPJ number.']
    8787>>> f.clean('64.132.916/0001-88')
    88 '64.132.916/0001-88'
     88u'64.132.916/0001-88'
    8989>>> f.clean('64-132-916/0001-88')
    90 '64-132-916/0001-88'
     90u'64-132-916/0001-88'
    9191>>> f.clean('64132916/0001-88')
    92 '64132916/0001-88'
     92u'64132916/0001-88'
    9393>>> f.clean('64.132.916/0001-XX')
    9494Traceback (most recent call last):
    9595...
     
    9797>>> f = BRCNPJField(required=False)
    9898>>> f.clean('')
    9999u''
     100>>> f.clean('64.132.916/0001-8')
     101Traceback (most recent call last):
     102...
     103ValidationError: [u'This field requires at least 14 digits']
     104>>> f.clean('6413291600018')
     105Traceback (most recent call last):
     106...
     107ValidationError: [u'Ensure this value has at least 14 characters (it has 13).']
     108>>> f.clean('64.132.916/0001-889')
     109Traceback (most recent call last):
     110...
     111ValidationError: [u'Ensure this value has at most 18 characters (it has 19).']
     112>>> from django.contrib.localflavor.br.forms import BRCNPJField
     113>>> f = BRCNPJField(return_format=BRCNPJField.DIGITS_ONLY)
     114>>> f.clean('12-345-678/9012-10')
     115Traceback (most recent call last):
     116...
     117ValidationError: [u'Invalid CNPJ number.']
     118>>> f.clean('64.132.916/0001-88')
     119u'64132916000188'
     120>>> f.clean('64132916000188')
     121u'64132916000188'
     122>>> f.clean('64132916/0001-88')
     123u'64132916000188'
     124>>> f = BRCNPJField(return_format=BRCNPJField.DOTS_SLASH_DASH)
     125>>> f.clean('64132916/0001-88')
     126u'64.132.916/0001-88'
     127>>> f.clean('64132916000188')
     128u'64.132.916/0001-88'
     129>>> f.clean('64.132.916/0001-88')
     130u'64.132.916/0001-88'
     131>>> f = BRCNPJField(return_format='%s%s%s/%s%s')
     132>>> f.clean('64132916/0001-88')
     133u'64132916/000188'
     134>>> f.clean('64132916000188')
     135u'64132916/000188'
     136>>> f.clean('64.132.916/0001-88')
     137u'64132916/000188'
     138>>> f = BRCNPJField(return_format='%s%s%s/%s%s', required=False)
     139>>> f.clean('')
     140u''
    100141
    101142# BRCPFField #################################################################
    102143
     
    151192u''
    152193>>> f.clean(None)
    153194u''
     195>>> f = BRCPFField(return_format=BRCPFField.DIGITS_ONLY)
     196>>> f.clean('')
     197Traceback (most recent call last):
     198...
     199ValidationError: [u'This field is required.']
     200>>> f.clean('663.256.017-26')
     201u'66325601726'
     202>>> f.clean('66325601726')
     203u'66325601726'
     204>>> f = BRCPFField(return_format=BRCPFField.DOTS_AND_DASH)
     205>>> f.clean('663.256.017-26')
     206u'663.256.017-26'
     207>>> f.clean('66325601726')
     208u'663.256.017-26'
     209>>> f = BRCPFField(return_format='%s%s%s-%s')
     210>>> f.clean('663.256.017-26')
     211u'663256017-26'
     212>>> f.clean('66325601726')
     213u'663256017-26'
     214>>> f = BRCPFField(return_format='%s%s%s-%s', required=False)
     215>>> f.clean('')
     216u''
     217>>> f.clean('000.000.000-00')
     218Traceback (most recent call last):
     219...
     220ValidationError: [u'Invalid CPF number.']
     221>>> f.clean('444.444.444-44')
     222Traceback (most recent call last):
     223...
     224ValidationError: [u'Invalid CPF number.']
     225>>> f.clean('999.999.999-99')
     226Traceback (most recent call last):
     227...
     228ValidationError: [u'Invalid CPF number.']
    154229
    155230# BRPhoneNumberField #########################################################
    156231
Back to Top