Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions localflavor/br/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,3 +197,51 @@ def clean(self, value):
raise ValidationError(self.error_messages['invalid'])

return orig_value


def mod_97_base10(value):
return 98 - ((value * 100 % 97) % 97)


class BRProcessoField(CharField):
"""
A form field that validates a Legal Process(Processo) number or a Legal Process string.
A Processo number is
compounded by NNNNNNN-DD.AAAA.J.TR.OOOO. The two DD digits are check digits.
More information:
http://www.cnj.jus.br/atos-administrativos/12179:resolucao-no-65-de-16-de-dezembro-de-2008
"""
default_error_messages = {
'invalid': _("Invalid Process number."),
'max_digits': _("This field requires at most 20 digits or 25 characters."),
'digits_only': _("This field requires only numbers."),
}

def __init__(self, max_length=25, min_length=20, *args, **kwargs):
super(BRProcessoField, self).__init__(max_length, min_length, *args, **kwargs)

def clean(self, value):
"""
Value can be either a string in the format NNNNNNN-DD.AAAA.J.TR.OOOO or an
20-digit number.
"""
value = super(BRProcessoField, self).clean(value)
if value in EMPTY_VALUES:
return ''
orig_value = value[:]
if not value.isdigit():
value = re.sub("[-\. ]", "", value)
try:
int(value)
except ValueError:
raise ValidationError(self.error_messages['digits_only'])
if len(value) != 20:
raise ValidationError(self.error_messages['max_digits'])
orig_dv = value[7:9]

value_without_digits = int(value[0:7] + value[9:])

if str(mod_97_base10(value_without_digits)).zfill(2) != orig_dv:
raise ValidationError(self.error_messages['invalid'])

return orig_value