Created
May 3, 2018 23:46
-
-
Save CelesteComet/f956a33ae5d41945e592ae03bbf89ca4 to your computer and use it in GitHub Desktop.
CPF Validation for Brazil
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
function cpfValidate(str) { | |
let match = str.match(/^(\d{9})-(\d{2})$/); | |
if (!match) { return false } | |
// If in the correct format | |
let firstSetString = match[1]; | |
let secondSetString = match[2]; | |
let sum = 0; | |
for (let i = 0; i < firstSetString.length; i++) { | |
let char = firstSetString[i]; | |
let toMultiply = 10 - i; | |
sum += Number(char) * toMultiply; | |
} | |
let simpleStepRes = (sum * 10) % 11; | |
if (simpleStepRes === 10) { simpleStepRes = 0 } | |
if (simpleStepRes.toString() !== secondSetString[0]) { return false; } | |
sum = 0; | |
let firstSetString2 = firstSetString + simpleStepRes.toString(); | |
for (let i = 0; i < firstSetString2.length; i++) { | |
let char = firstSetString2[i]; | |
let toMultiply = 11 - i; | |
sum += Number(char) * toMultiply; | |
} | |
let simpleStepRes2 = (sum * 10) % 11; | |
if (simpleStepRes2 === 10) { simpleStepRes2 = 0 } | |
if (simpleStepRes2.toString() !== secondSetString[1]) { return false; } | |
return true; | |
} | |
console.log(cpfValidate("d840608472-32aw")) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment