Skip to content

Instantly share code, notes, and snippets.

@jaronwanderley
Last active June 16, 2021 12:45
Show Gist options
  • Save jaronwanderley/c06220e19092700c12e63c2ad4c32c12 to your computer and use it in GitHub Desktop.
Save jaronwanderley/c06220e19092700c12e63c2ad4c32c12 to your computer and use it in GitHub Desktop.
Validation for CPF and CNPJ
const isString = value => typeof value === 'string'
const format = value => value.replace(/[^\d]+/g, '')
const isValidNumber = (value, count) => format(value).length === count && !format(value).match(/(\d)\1{10}/)
const validator = value => format(value)
.split('')
.splice(format(value).length - 2)
.map( el => +el )
const toValidate = (value, end, start = 0) => format(value)
.split('')
.filter((digit, index, array) => index >= start && index <= end && digit)
.map(el => +el)
const sum = (array, start) => array.reduce((total, el, i) => total + el * (start - i), 0)
const rest = value => value % 11
const validate = (firstDigit, lastDigit, validator) => firstDigit === validator[0] && lastDigit === validator[1]
function isValidCPF(cpf) {
if (!isString(cpf) || !isValidNumber(cpf, 11)) return false
digit = (end, factor) => rest(sum(toValidate(cpf,end),factor) * 10) % 10
const firstDigit = digit(8, 10)
const lastDigit = digit(9, 11)
return validate(firstDigit, lastDigit, validator(cpf))
}
function isValidCNPJ(cnpj) {
if (!isString(cnpj) || !isValidNumber(cnpj, 14)) return false
const digit = sum => rest(sum) < 2 ? 0 : 11 - rest(sum)
const firstDigit = digit(sum(toValidate(cnpj,3),5) + sum(toValidate(cnpj,11,4),9))
const lastDigit = digit(sum(toValidate(cnpj,4),6) + sum(toValidate(cnpj,12,5),9))
return validate(firstDigit, lastDigit, validator(cnpj))
}
@jaronwanderley
Copy link
Author

That's Amazing bro !
Congratulations you help me a lot

looool u r awesome too man!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment