h7-validate-cpf
Version:
A TypeScript library to validate Brazilian CPF, responsible by validate CPF | validate equals numbers | quantity of numbers and if is true or false
41 lines (40 loc) • 1.09 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.VerifyCPF = void 0;
/**
* @author
* @see https://github.com/herlandio
*
* Class responsible for validating CPF
*/
class VerifyCPF {
/**
* Verify digits of CPF
*
* @param {string | number} cpf
* @param {number} digit
* @returns {string}
*/
verifyDigits(cpf, digit) {
let digits = 0;
for (let start = 0; start < cpf.toString().length && digit >= 2; start++, digit--) {
digits += Number(cpf.toString()[start]) * digit;
}
digits %= 11;
const verify = digits < 2 ? 0 : 11 - digits;
return cpf.toString() + verify;
}
/**
* Verify CPF
*
* @param {string | number} cpf
* @returns {boolean}
*/
verifyCPF(cpf) {
const cleanCpf = cpf.toString().replace(/\D+/g, "");
return /(\d)\1{10}/.test(cleanCpf)
? false
: cleanCpf === this.verifyDigits(this.verifyDigits(cleanCpf, 10).substring(0, 10), 11);
}
}
exports.VerifyCPF = VerifyCPF;