Created
April 11, 2021 03:54
-
-
Save RuanAragao/a0022c51c48385bf266402538542b25d to your computer and use it in GitHub Desktop.
Como validar CPF javascript nodejs
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
const readline = require("readline"); | |
const rl = readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout | |
}); | |
function digitResover(val) { | |
// LM = 11k + r | |
const k = 11; // Quociente | |
const r = val%k; // Resto | |
if (r == 0 || r == 1) { | |
return 0; | |
} | |
return k-r; | |
} | |
function calcL(d) { | |
const L = 10*d[0]+ | |
9*d[1]+ | |
8*d[2]+ | |
7*d[3]+ | |
6*d[4]+ | |
5*d[5]+ | |
4*d[6]+ | |
3*d[7]+ | |
2*d[8]; | |
return digitResover(L); | |
} | |
function calcM(d) { | |
const M = 10*d[1]+ | |
9*d[2]+ | |
8*d[3]+ | |
7*d[4]+ | |
6*d[5]+ | |
5*d[6]+ | |
4*d[7]+ | |
3*d[8]+ | |
2*d[9]; | |
return digitResover(M); | |
} | |
function check(cpfVal) { | |
const digits = cpfVal.split(""); | |
if ( | |
digits[9] == calcL(digits) && | |
digits[10] == calcM(digits) | |
) { | |
return true; | |
} | |
return false; | |
} | |
rl.question("CPF: ", function (digits) { | |
console.log( check(digits) ) | |
rl.close() | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment