Skip to content

Commit

Permalink
Merge pull request #14 from lleao/feature/desacoplarMOD11
Browse files Browse the repository at this point in the history
- Separação do MOD11 da validação
  • Loading branch information
AZagatti authored Aug 17, 2020
2 parents 33ec860 + ded822f commit 223b10f
Show file tree
Hide file tree
Showing 6 changed files with 86 additions and 73 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
node_modules
/lib
coverage
coverage
.history/
5 changes: 2 additions & 3 deletions src/__tests__/usevalidationsbr.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,14 @@ describe('UseValidationBr CNPJ', () => {
});

describe('UseValidationBr CPF', () => {
it('should be able return true to valid CNPJ', () => {
it('should be able return true to valid CPF', () => {
expect.assertions(3);

expect(useValidationsBR('cpf', '248.283.728-65')).toBe(true);
expect(useValidationsBR('cpf', '241.845.620-00')).toBe(true);
expect(useValidationsBR('cpf', '551.137.567-50')).toBe(true);
});

it('should be able return false to invalid CNPJ', () => {
it('should be able return false to invalid CPF', () => {
expect.assertions(2);

expect(useValidationsBR('cpf', '248.283.728-66')).toBe(false);
Expand Down
13 changes: 8 additions & 5 deletions src/__tests__/validateCPF.spec.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
import { validateCPF } from '../index';

describe('Validate CNPJ', () => {
it('should be able return true to valid CNPJ', () => {
expect.assertions(3);
describe('Validate CPF', () => {
it('should be able return true to valid CPF', () => {
expect.assertions(4);

expect(validateCPF('012.345.678-90')).toBe(true);
expect(validateCPF('248.283.728-65')).toBe(true);
expect(validateCPF('241.845.620-00')).toBe(true);
expect(validateCPF('551.137.567-50')).toBe(true);
});

it('should be able return false to invalid CNPJ', () => {
expect.assertions(2);
it('should be able return false to invalid CPF', () => {
expect.assertions(3);

expect(validateCPF('248.283.728-66')).toBe(false);
expect(validateCPF('425.719.798-04')).toBe(false);
expect(validateCPF('012.345.678-91')).toBe(false);
});

it('should be able return false to pass a empty string', () => {
Expand All @@ -22,5 +24,6 @@ describe('Validate CNPJ', () => {

it('should be able return false to pass a only repeated numbers', () => {
expect(validateCPF('000.000.000-00')).toBe(false);
expect(validateCPF('111.111.111-11')).toBe(false);
});
});
24 changes: 24 additions & 0 deletions src/validations/mod11.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* Calcula o MOD11 para o número informado
* @param valor Número base para o calculo
* @param limite Limite da casa de multiplicação
* Para CPF assume o valor de 12, para CNPJ o valor de 9.
* @returns Retorna o DV calculado
*/
export const mod11: (v: string, l: number) => number = (
clearValue: string,
limite: number,
) => {
const valor = String(clearValue).replace(/\D/g, '');
let sum = 0;
let mult = 2;

for (let i = valor.length - 1; i >= 0; i--) {
sum += mult * +valor[i];
if (++mult > limite) {
mult = 2;
}
}
const dv = ((sum * 10) % 11) % 10;
return dv;
};
54 changes: 18 additions & 36 deletions src/validations/validateCNPJ.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
import { mod11 } from './mod11';

/**
* Valida o CNPJ. A entrada pode ser com ou sem máscaras.
* O tamanho deve ser respeitado como em '00.000.000/0000-00' ou '00000000000000'.
* @param value
* @returns True se o CNPJ é válido, falso caso contrário
*/
export function validateCNPJ(value: string): boolean {
const clearValue = String(value).replace(/[^\d]+/g, '');

// Campo sem máscara
if (clearValue === '') return false;

// Tamanho diferente do exigido
if (clearValue.length !== 14) return false;

// Valores carteados já conhecidos como inválidos
if (
clearValue === '00000000000000' ||
clearValue === '11111111111111' ||
Expand All @@ -16,39 +24,13 @@ export function validateCNPJ(value: string): boolean {
clearValue === '77777777777777' ||
clearValue === '88888888888888' ||
clearValue === '99999999999999'
)
) {
return false;

let length = clearValue.length - 2;
let numbers = clearValue.substring(0, length);
const digits = clearValue.substring(length);
let sum = 0;
let position = length - 7;

for (let i = length; i >= 1; i -= 1) {
sum += +numbers.charAt(length - i) * position;
position -= 1;
if (position < 2) position = 9;
}

let result = sum % 11 < 2 ? 0 : 11 - (sum % 11);

if (result !== +digits.charAt(0)) return false;

length += 1;
numbers = clearValue.substring(0, length);
sum = 0;
position = length - 7;

for (let i = length; i >= 1; i -= 1) {
sum += +numbers.charAt(length - i) * position;
position -= 1;
if (position < 2) position = 9;
}

result = sum % 11 < 2 ? 0 : 11 - (sum % 11);

if (result !== +digits.charAt(1)) return false;

return true;
// O CNPJ possui 2 DVs, excluíndo para validar
const valWithoutDvs = clearValue.substring(0, clearValue.length - 2);
const dv1 = mod11(valWithoutDvs, 9);
const dv2 = mod11(valWithoutDvs + dv1, 9);
// Compara com a informação passada como paramêtro
return valWithoutDvs + dv1 + dv2 === clearValue;
}
60 changes: 32 additions & 28 deletions src/validations/validateCPF.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,35 @@
import { mod11 } from './mod11';

/**
* Função que valida se a string é apenas
* números repetidos.
*
* @param ref String númerica
* @returns True se for contida por apenas caracteres repetidos,
* false caso contrário
*/
const isRepeated = (ref: string) => {
const ret = ref.replace(new RegExp(ref[0], 'g'), '').trim().length === 0;
return ret;
};
/**
* Valida o CPF. A entrada pode ser com ou sem máscaras.
* O tamanho deve ser respeitado como em '000.000.000-00' ou '00000000000'.
* @param value
*/
export function validateCPF(value: string): boolean {
// Campo sem máscara
const clearValue = String(value).replace(/\D/g, '');
let sum = 0;
let rest;

if (clearValue === '') return false;

if (clearValue === '00000000000') return false;

for (let i = 1; i <= 9; i += 1)
sum += +clearValue.substring(i - 1, i) * (11 - i);

rest = (sum * 10) % 11;

if (rest === 10 || rest === 11) rest = 0;

if (rest !== +clearValue.substring(9, 10)) return false;

sum = 0;

for (let i = 1; i <= 10; i += 1)
sum += +clearValue.substring(i - 1, i) * (12 - i);

rest = (sum * 10) % 11;

if (rest === 10 || rest === 11) rest = 0;

if (rest !== +clearValue.substring(10, 11)) return false;

return true;
// O CPF possui 2 DVs, excluíndo para validar
const valWithoutDvs = clearValue.substring(0, clearValue.length - 2);
// Valida se está vazio ou é valor repetido
if (!clearValue || isRepeated(clearValue)) {
return false;
}
// Calcula o primeiro DV
const dv1 = mod11(valWithoutDvs, 12);
// Calcula o segundo DV2
const dv2 = mod11(valWithoutDvs + dv1, 12);
// Compara com a informação passada como paramêtro
return valWithoutDvs + dv1 + dv2 === clearValue;
}

0 comments on commit 223b10f

Please sign in to comment.