Validate CPF js

Jarod Cavalcante
2021-11-24T18:49:19Z

validateCPF.js

| 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);
| }