Created
November 27, 2012 00:12
-
-
Save scardine/4151525 to your computer and use it in GitHub Desktop.
CNPJ (Brazilian tax id) format validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#------------------------------------------------------------------------------- | |
# Name: validate_cnpj | |
# Purpose: check formal validity of a cnpj number (brazilian tax id) | |
# this only checks if the digits match, not if the number is | |
# valid at Receita Federal (Brazilian IRS) | |
# | |
# Author: Paulo Scardine <[email protected]> | |
# | |
# Created: 26/11/2012 | |
# Copyright: (c) PauloS 2012 | |
# Licence: BSD | |
#------------------------------------------------------------------------------- | |
#!/usr/bin/env python | |
def xtend_validate_cnpj(cnpj): | |
# Filter out non digits and pad with 0 until length is 15 | |
cnpj = ''.join([ c for c in cnpj if c in '0123456789']).rjust(15, '0') | |
# If more then 15 digits or all 0s, reject | |
if len(cnpj) != 15 or cnpj == '0' * 15: return False | |
# Check first digit | |
j = 2; s1 = 0 | |
for i in range(12, -1, -1): | |
s1 += int(cnpj[i]) * j | |
j += 1 | |
if j > 9: j = 2 | |
r = s1 % 11 | |
if int(cnpj[13]) != (0 if r < 2 else 11 - r): return False | |
# Check second digit | |
j = 2; s2 = 0 | |
for i in range(13, -1, -1): | |
s2 += int(cnpj[i]) * j | |
j += 1 | |
if j > 9: j = 2 | |
r = s2 % 11 | |
return int(cnpj[14]) == (0 if r < 2 else 11 - r) | |
def main(): | |
for cnpj in ('012345678000100', '012345678000190', '012345678000195'): | |
print cnpj, ':', | |
print xtend_validate_cnpj(cnpj) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment