Skip to content

Commit

Permalink
fix: Fix CPF validation for invalid length The code changes in cpfVal…
Browse files Browse the repository at this point in the history
…idator.ts fix the validation for CPFs with an invalid length. Previously, the code only checked for a length of 11 or 14, but now it correctly returns an error message when the length is not 11. This ensures that the CPF validation is accurate and reliable.
  • Loading branch information
gabriel-logan committed Jun 14, 2024
1 parent d28c2e5 commit fd9e76a
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
14 changes: 8 additions & 6 deletions packages/typescript/src/cpfValidator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,7 @@ function cpfIsValid(
let numeroBase2: number = 11;
let somaTotal: number = 0;
let somaTotal2: number = 0;
if (cpf.length !== 11 && cpf.length !== 14) {
return {
isValid: false,
errorMsg: getErrorMessage(1),
};
}

const cpfLimpo: string = cpf.replace(/\D+/g, ""); // Transforma o cpf em um valor limpo sem caracter especial
// Validação para verificar se todos os dígitos são iguais (condição de CPF inválido).
if (/^(\d)\1{10}$/.test(cpfLimpo)) {
Expand All @@ -77,6 +72,13 @@ function cpfIsValid(
};
}

if (cpfLimpo.length !== 11) {
return {
isValid: false,
errorMsg: getErrorMessage(1),
};
}

let primeiroVerificador: number = 0;
let segundoVerificador: number = 0;

Expand Down
2 changes: 1 addition & 1 deletion packages/typescript/tests/src/cpfValidator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ describe('cpfIsValid', () => {
it('should return isValid as false and the correct error message when CPF is invalid', () => {
const result = cpfIsValid('123456789-02');
expect(result.isValid).toBe(false);
expect(result.errorMsg).toBe("CPF must have 11 numerical digits");
expect(result.errorMsg).toBe("CPF is not valid");
});

it('should throw an error when the input is not a string', () => {
Expand Down

0 comments on commit fd9e76a

Please sign in to comment.