| 40 | |
| 41 | def DV_maker(v): |
| 42 | if v >= 2: |
| 43 | return 11 - v |
| 44 | return 0 |
| 45 | |
| 46 | class BRCNPJField(Field): |
| 47 | def clean(self, value): |
| 48 | """ value can be either a string in the format XX.XXX.XXX/XXXX-XX |
| 49 | or a group of 14 characters. """ |
| 50 | if not value.isdigit(): |
| 51 | value = re.sub("[-/\.]", "", value) |
| 52 | if len(value) != 14: |
| 53 | raise ValidationError( |
| 54 | gettext(u"This field requires at least 14 digits")) |
| 55 | orig_value = value[:] |
| 56 | orig_dv = value[-2:] |
| 57 | |
| 58 | new_1dv = sum([i * int(value[idx]) |
| 59 | for idx, i in enumerate(range(5, 1, -1) + |
| 60 | range(9, 1, -1))]) |
| 61 | new_1dv = DV_maker(new_1dv % 11) |
| 62 | value = value[:-2] + str(new_1dv) + value[-1] |
| 63 | new_2dv = sum([i * int(value[idx]) |
| 64 | for idx, i in enumerate(range(6, 1, -1) + |
| 65 | range(9, 1, -1))]) |
| 66 | new_2dv = DV_maker(new_2dv % 11) |
| 67 | value = value[:-1] + str(new_2dv) |
| 68 | if (value[-2:] != orig_dv): |
| 69 | raise ValidationError(gettext(u"Invalid CNPJ number")) |
| 70 | |
| 71 | return orig_value |
| 72 | |