Created
November 24, 2021 18:49
-
-
Save jarodsim/d0e2b68e715259f31051e5c4e5ba7b96 to your computer and use it in GitHub Desktop.
Validate CPF js
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 _validateCPF( | |
value: string, | |
handleResponse: (value: Record<string, unknown>) => void | |
): void { | |
let data = {}; | |
let sum; | |
let rest; | |
sum = 0; | |
if (value === '000.000.000-00') { | |
data = { value: false, error: 'invalidCpf' }; | |
handleResponse(data); | |
return; | |
} | |
const valueReplaced = value | |
.replace('.', '') | |
.replace('.', '') | |
.replace('-', ''); | |
for (let i = 1; i <= 9; i++) | |
sum = sum + parseInt(valueReplaced.substring(i - 1, i)) * (11 - i); | |
rest = (sum * 10) % 11; | |
if (rest === 10 || rest === 11) rest = 0; | |
if (rest != parseInt(valueReplaced.substring(9, 10))) { | |
data = { value: false, error: 'invalidCpf' }; | |
handleResponse(data); | |
return; | |
} | |
sum = 0; | |
for (let i = 1; i <= 10; i++) | |
sum = sum + parseInt(valueReplaced.substring(i - 1, i)) * (12 - i); | |
rest = (sum * 10) % 11; | |
if (rest === 10 || rest === 11) rest = 0; | |
if (rest != parseInt(valueReplaced.substring(10, 11))) { | |
data = { value: false, error: 'invalidCpf' }; | |
handleResponse(data); | |
return; | |
} | |
data = { value: true, error: '' }; | |
handleResponse(data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment