Validar CPF / CNPJ
- Alfredo Bernal
Owned by Alfredo Bernal
May 17, 2024
2 min read
Loading data...
Ejemplos proporcionados en TypeScript
import { IValidator } from "../interfaces/validator";
export class CpfValidator implements IValidator {
private BLACKLIST: Array<string> = [
'00000000000',
'11111111111',
'22222222222',
'33333333333',
'44444444444',
'55555555555',
'66666666666',
'77777777777',
'88888888888',
'99999999999',
'12345678909'
]
private LOOSE_STRIP_REGEX: RegExp = /[^\d]/g;
valid(arg: string): boolean {
const stripped: string = this.strip(arg);
// CPF must be defined
if (!stripped) {
return false
}
// CPF must have 11 chars
if (stripped.length !== 11) {
return false
}
// CPF can't be blacklisted
if (this.BLACKLIST.includes(stripped)) {
return false
}
let numbers: string = stripped.substring(0, 9);
numbers += this.verifierDigit(numbers);
numbers += this.verifierDigit(numbers);
return numbers.substring(-2) === stripped.substring(-2);
}
private strip = (number: string): string => {
const regex: RegExp = this.LOOSE_STRIP_REGEX;
return (number || '').replace(regex, '');
}
private verifierDigit = (digits: string): number => {
const numbers: Array<number> = digits
.split('')
.map(number => {
return parseInt(number, 10)
})
const modulus: number = numbers.length + 1
const multiplied: Array<number> = numbers.map((number, index) => number * (modulus - index))
const mod: number = multiplied.reduce((buffer, number) => buffer + number) % 11
return (mod < 2 ? 0 : 11 - mod)
}
}
import { IValidator } from "../interfaces/validator";
export class CnpjValidator implements IValidator {
private BLACKLIST: Array<string> = [
'00000000000000',
'11111111111111',
'22222222222222',
'33333333333333',
'44444444444444',
'55555555555555',
'66666666666666',
'77777777777777',
'88888888888888',
'99999999999999'
];
private LOOSE_STRIP_REGEX: RegExp = /[^\d]/g;
valid(arg: string): boolean {
const stripped: string = this.strip(arg);
// CNPJ must be defined
if (!stripped) {
return false;
}
// CNPJ must have 14 chars
if (stripped.length !== 14) {
return false;
}
// CNPJ can't be blacklisted
if (this.BLACKLIST.includes(stripped)) {
return false;
}
let numbers: string = stripped.substring(0, 12);
numbers += this.verifierDigit(numbers);
numbers += this.verifierDigit(numbers);
return numbers.substring(-2) === stripped.substring(-2);
}
private strip = (number: string): string => {
const regex: RegExp = this.LOOSE_STRIP_REGEX;
return (number || '').replace(regex, '');
}
private verifierDigit = (digits: string): number => {
let index: number = 2
const reverse: Array<number> = digits.split('').reduce((buffer, number) => {
return [parseInt(number, 10)].concat(buffer)
}, []);
const sum: number = reverse.reduce((buffer, number) => {
buffer += number * index;
index = (index === 9 ? 2 : index + 1);
return buffer;
}, 0)
const mod: number = sum % 11;
return (mod < 2 ? 0 : 11 - mod);
}
}
export interface IValidator {
valid(arg?: any): boolean;
}