Last active
June 16, 2021 12:45
-
-
Save jaronwanderley/c06220e19092700c12e63c2ad4c32c12 to your computer and use it in GitHub Desktop.
Validation for CPF and 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
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)) | |
} |
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
That's Amazing bro !
Congratulations you help me a lot
Thank's