Created
April 2, 2018 13:13
-
-
Save alexpvieira/ed40e43a9b5f48749b0d409374c4406d to your computer and use it in GitHub Desktop.
Validate CNPJ
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
export default function validateCNPJ(cnpj) { | |
if (cnpj == '') return false | |
if (cnpj.length != 14) return false | |
if (cnpj == "00000000000000" || | |
cnpj == "11111111111111" || | |
cnpj == "22222222222222" || | |
cnpj == "33333333333333" || | |
cnpj == "44444444444444" || | |
cnpj == "55555555555555" || | |
cnpj == "66666666666666" || | |
cnpj == "77777777777777" || | |
cnpj == "88888888888888" || | |
cnpj == "99999999999999") return false; | |
let size = cnpj.length - 2 | |
let numbers = cnpj.substring(0, size) | |
let digits = cnpj.substring(size) | |
let sum = 0 | |
let pos = size - 7 | |
for (let i = size; i >= 1; i--) { | |
sum += numbers.charAt(size - i) * pos-- | |
if (pos < 2) pos = 9 | |
} | |
let result = sum % 11 < 2 ? 0 : 11 - sum % 11 | |
if (result != digits.charAt(0)) return false | |
size = size + 1 | |
numbers = cnpj.substring(0, size) | |
sum = 0 | |
pos = size - 7 | |
for (let i = size; i >= 1; i--) { | |
sum += numbers.charAt(size - i) * pos-- | |
if (pos < 2) pos = 9 | |
} | |
result = sum % 11 < 2 ? 0 : 11 - sum % 11 | |
if (result != digits.charAt(1)) return false | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment