|
| 1 | +/* eslint-disable @typescript-eslint/no-magic-numbers */ |
| 2 | + |
| 3 | +import { getTypeof } from "../get-typeof"; |
| 4 | + |
| 5 | +/* |
| 6 | + * CPF validation according to Receita Federal |
| 7 | + * More info: https://www.geradorcnpj.com/algoritmo_do_cnpj.htm |
| 8 | + */ |
| 9 | + |
| 10 | +const notCnpj = [ |
| 11 | + "00000000000000", |
| 12 | + "11111111111111", |
| 13 | + "22222222222222", |
| 14 | + "33333333333333", |
| 15 | + "44444444444444", |
| 16 | + "55555555555555", |
| 17 | + "66666666666666", |
| 18 | + "77777777777777", |
| 19 | + "88888888888888", |
| 20 | + "99999999999999", |
| 21 | +]; |
| 22 | + |
| 23 | +/** |
| 24 | + * Check if a string is a valid cpf |
| 25 | + * - 55357314047 |
| 26 | + */ |
| 27 | +export const isCnpj = (cnpj: string) => { |
| 28 | + if (getTypeof(cnpj) !== "string") return false; |
| 29 | + |
| 30 | + if (cnpj === "") return false; |
| 31 | + |
| 32 | + if (cnpj.length !== 14) return false; |
| 33 | + |
| 34 | + if (notCnpj.includes(cnpj)) return false; |
| 35 | + |
| 36 | + let length = cnpj.length - 2; |
| 37 | + let numbers = cnpj.substring(0, length); |
| 38 | + const digits = cnpj.substring(length); |
| 39 | + let sum = 0; |
| 40 | + let pos = length - 7; |
| 41 | + |
| 42 | + for (let i = length; i >= 1; i--) { |
| 43 | + const nbr = parseInt(numbers.charAt(length - i), 10); |
| 44 | + |
| 45 | + sum += nbr * pos--; |
| 46 | + |
| 47 | + if (pos < 2) pos = 9; |
| 48 | + } |
| 49 | + |
| 50 | + let result = sum % 11 < 2 ? 0 : 11 - (sum % 11); |
| 51 | + |
| 52 | + const firstChar = parseInt(digits.charAt(0), 10); |
| 53 | + |
| 54 | + if (result !== firstChar) return false; |
| 55 | + |
| 56 | + length += 1; |
| 57 | + numbers = cnpj.substring(0, length); |
| 58 | + sum = 0; |
| 59 | + pos = length - 7; |
| 60 | + |
| 61 | + for (let i = length; i >= 1; i--) { |
| 62 | + const nbr = parseInt(numbers.charAt(length - i), 10); |
| 63 | + |
| 64 | + sum += nbr * pos--; |
| 65 | + |
| 66 | + if (pos < 2) pos = 9; |
| 67 | + } |
| 68 | + |
| 69 | + result = sum % 11 < 2 ? 0 : 11 - (sum % 11); |
| 70 | + |
| 71 | + const secondChar = parseInt(digits.charAt(1), 10); |
| 72 | + |
| 73 | + if (result !== secondChar) return false; |
| 74 | + |
| 75 | + return true; |
| 76 | +}; |
0 commit comments