Created
December 4, 2022 01:51
-
-
Save richardiwnl/d404fe7ae39289756328b04a4a29618d to your computer and use it in GitHub Desktop.
Validador de CPF em JavaScript
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 ValidaCPF(cpfEnviado) { | |
Object.defineProperty(this, "cpfLimpo", { | |
enumerable: true, | |
get: function() { | |
return cpfEnviado.replace(/\D+/g, ''); | |
} | |
}); | |
} | |
ValidaCPF.prototype.valida = function() { | |
if (typeof this.cpfLimpo == "undefined") return false; | |
if (this.cpfLimpo.length !== 11) return false; | |
if (this.isSequencia()) return false; | |
const cpfParcial = this.cpfLimpo.slice(0, -2); | |
const digito1 = this.criaDigito(cpfParcial); | |
const digito2 = this.criaDigito(cpfParcial + digito1); | |
const novoCpf = cpfParcial + digito1 + digito2; | |
return novoCpf === this.cpfLimpo; | |
}; | |
ValidaCPF.prototype.criaDigito = function(cpfParcial) { | |
const cpfArray = Array.from(cpfParcial); | |
let regressivo = cpfArray.length + 1; | |
const total = cpfArray.reduce((ac, val) => { | |
ac += (regressivo * Number(val)); | |
regressivo--; | |
return ac; | |
}, 0); | |
const digito = 11 - (total % 11); | |
return digito > 9 ? '0' : String(digito); | |
} | |
ValidaCPF.prototype.isSequencia = function() { | |
return this.cpfLimpo[0].repeat(this.cpfLimpo.length) === this.cpfLimpo; | |
} | |
const cpf = new ValidaCPF("235.333.500-45"); | |
console.log(cpf.valida()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment