Skip to content

Instantly share code, notes, and snippets.

@gerardo-junior
Last active February 3, 2022 14:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gerardo-junior/79500e5200d2a6e8f6295006aa0d8399 to your computer and use it in GitHub Desktop.
Save gerardo-junior/79500e5200d2a6e8f6295006aa0d8399 to your computer and use it in GitHub Desktop.
Function to validate a CPF and CNPJ
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
}
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