@danielnogueira808/validations-libs
Version:
```sh npm i --save @danielnogueira808/validations-libs ``` # how to use ``` import { isCNPJ, isCPF } from "@danielnogueira808/validations-libs";
42 lines (31 loc) • 1.15 kB
text/typescript
// Pure validation functions
const cleanCPFDigits = (str: string): string =>
str.replace(/\D/g, '');
const isValidLength = (cpf: string): boolean =>
cpf.length === 11;
const hasRepeatedDigits = (cpf: string): boolean =>
/^(\d)\1{10}$/.test(cpf);
const calculateDigit = (cpf: string, length: number): number => {
const sum = [...cpf]
.slice(0, length)
.reduce((acc, digit, index) =>
acc + parseInt(digit) * ((length + 1) - index), 0);
const remainder = sum % 11;
return remainder < 2 ? 0 : 11 - remainder;
};
const validateVerificationDigits = (cpf: string): boolean => {
const digit1 = calculateDigit(cpf, 9);
const digit2 = calculateDigit(cpf, 10);
return (
digit1 === parseInt(cpf.charAt(9)) &&
digit2 === parseInt(cpf.charAt(10))
);
};
// Main validation function following Single Responsibility Principle
export function isCPF(str: string): boolean {
if (!str) return false;
const cpf = cleanCPFDigits(str);
if (!isValidLength(cpf)) return false;
if (hasRepeatedDigits(cpf)) return false;
return validateVerificationDigits(cpf);
}