Advertisement
eappereira

Validação Javascript CNPJ

Jan 15th, 2015
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!--  
  2.     Elton Pereira - eltondeveloper@gmail.com
  3.     Função de validação CNPJ
  4. -->
  5.  
  6.  
  7. function ValidaCNPJ(cnpj) {
  8.     cnpj = cnpj.replace(/[^\d]+/g,'');
  9.     if(cnpj == '') return false;
  10.     if (cnpj.length != 14)
  11.         return false;  
  12.     if (cnpj == "00000000000000" ||
  13.         cnpj == "11111111111111" ||
  14.         cnpj == "22222222222222" ||
  15.         cnpj == "33333333333333" ||
  16.         cnpj == "44444444444444" ||
  17.         cnpj == "55555555555555" ||
  18.         cnpj == "66666666666666" ||
  19.         cnpj == "77777777777777" ||
  20.         cnpj == "88888888888888" ||
  21.         cnpj == "99999999999999")
  22.         return false;
  23.     tamanho = cnpj.length - 2
  24.     numeros = cnpj.substring(0,tamanho);
  25.     digitos = cnpj.substring(tamanho);
  26.     soma = 0;
  27.     pos = tamanho - 7;
  28.     for (i = tamanho; i >= 1; i--) {
  29.       soma += numeros.charAt(tamanho - i) * pos--;
  30.       if (pos < 2)
  31.             pos = 9;
  32.     }
  33.     resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
  34.     if (resultado != digitos.charAt(0))
  35.         return false;
  36.     tamanho = tamanho + 1;
  37.     numeros = cnpj.substring(0,tamanho);
  38.     soma = 0;
  39.     pos = tamanho - 7;
  40.     for (i = tamanho; i >= 1; i--) {
  41.       soma += numeros.charAt(tamanho - i) * pos--;
  42.       if (pos < 2)
  43.             pos = 9;
  44.     }
  45.     resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
  46.     if (resultado != digitos.charAt(1))
  47.           return false;
  48.     return true;
  49. }
  50.  
  51.  
  52. <!-- Para utilizar a função aplique -->
  53.  
  54. window.onload = function (){
  55.   var cnpj = document.getElementById('reg_billing_cnpj');
  56.   cnpj.onblur = function(){
  57.     var valid = ValidaCNPJ(this.value);
  58.     if(valid == false){
  59.       alert("Informe um CNPJ válido");
  60.       cnpj.focus();
  61.       return (false);    
  62.     }
  63.   }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement