Created
          February 8, 2024 14:04 
        
      - 
      
 - 
        
Save willsza/cbbf06d331916511fc810b9cad0c3eef to your computer and use it in GitHub Desktop.  
    Validação de CNPJ
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | function validaCNPJ(cnpj: string): boolean { | |
| cnpj = cnpj.replace(/\D/g, ''); | |
| if (cnpj.length !== 14 || /^(\d)\1+$/.test(cnpj)) return false; | |
| const calcularDigito = (base: number) => { | |
| const pesos = base === 12 ? [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2] : [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]; | |
| let soma = 0; | |
| for (let i = 0; i < base; i++) { | |
| soma += parseInt(cnpj.charAt(i)) * pesos[i]; | |
| } | |
| const resto = soma % 11; | |
| return resto < 2 ? 0 : 11 - resto; | |
| }; | |
| const digito1 = calcularDigito(12); | |
| const digito2 = calcularDigito(13); | |
| return cnpj.charAt(12) === digito1.toString() && cnpj.charAt(13) === digito2.toString(); | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment