Last active
February 3, 2022 14:24
-
-
Save gerardo-junior/79500e5200d2a6e8f6295006aa0d8399 to your computer and use it in GitHub Desktop.
Function to validate a CPF and CNPJ
This file contains hidden or 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
function isValidCNPJ(cnpj = '') { | |
cnpj = `${cnpj}`.replace(/^\D+/gmi, '') | |
if (cnpj.length != 14 || new Set(cnpj).size === 1) return false | |
size = cnpj.length - 2 | |
numbers = cnpj.substring(0, size) | |
digits = cnpj.substring(size) | |
soma = 0 | |
pos = size - 7 | |
for (i = size; i >= 1; i--) { | |
soma += numbers.charAt(size - i) * pos-- | |
if (pos < 2) | |
pos = 9 | |
} | |
result = soma % 11 < 2 ? 0 : 11 - soma % 11 | |
if (result != digits.charAt(0)) return false | |
size = size + 1 | |
numbers = cnpj.substring(0, size) | |
soma = 0 | |
pos = size - 7 | |
for (i = size; i >= 1; i--) { | |
soma += numbers.charAt(size - i) * pos-- | |
if (pos < 2) | |
pos = 9 | |
} | |
result = soma % 11 < 2 ? 0 : 11 - soma % 11 | |
if (result != digits.charAt(1)) return false | |
return true | |
} |
This file contains hidden or 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
function isValidCPF (cpf = '') { | |
let sum = 0, | |
remainder | |
cpf = `${cpf}`.replace(/^\D+/gmi, '') | |
if (cpf.length != 11 || new Set(cpf).size === 1) return false | |
for (let i = 1; i <= 9; i++) sum = sum + parseInt(cpf.substring(i - 1, i)) * (11 - i) | |
remainder = (sum * 10) % 11 | |
if (remainder == 10 || remainder == 11) remainder = 0 | |
if (remainder != parseInt(cpf.substring(9, 10))) return false | |
sum = 0 | |
for (let i = 1; i <= 10; i++) sum = sum + parseInt(cpf.substring(i - 1, i)) * (12 - i) | |
remainder = (sum * 10) % 11 | |
if (remainder == 10 || remainder == 11) remainder = 0 | |
if (remainder != parseInt(cpf.substring(10, 11))) return false | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment