CNPJ validation in Javascript

Asked

Viewed 17,029 times

0

I have a simple doubt. I want to validate the cnpj of an institution registration. In this input is already placed the mask, in which the mask is in js. However, I cannot validate this field. I took a famous example of the net, but it’s not working when putting in the input, someone knows the right code?

Obs: I’m using angular

function FormataCnpj(campo, teclapres)
			{
				var tecla = teclapres.keyCode;
				var vr = new String(campo.value);
				vr = vr.replace(".", "");
				vr = vr.replace("/", "");
				vr = vr.replace("-", "");
				tam = vr.length + 1;
				if (tecla != 14)
				{
					if (tam == 3)
						campo.value = vr.substr(0, 2) + '.';
					if (tam == 6)
						campo.value = vr.substr(0, 2) + '.' + vr.substr(2, 5) + '.';
					if (tam == 10)
						campo.value = vr.substr(0, 2) + '.' + vr.substr(2, 3) + '.' + vr.substr(6, 3) + '/';
					if (tam == 15)
						campo.value = vr.substr(0, 2) + '.' + vr.substr(2, 3) + '.' + vr.substr(6, 3) + '/' + vr.substr(9, 4) + '-' + vr.substr(13, 2);
				}
			}



function validarCNPJ(cnpj) {
 
    cnpj = cnpj.replace(/[^\d]+/g,'');
 
    if(cnpj == '') return false;
     
    if (cnpj.length != 14)
        return false;
 
    // Elimina CNPJs invalidos conhecidos
    if (cnpj == "00000000000000" || 
        cnpj == "11111111111111" || 
        cnpj == "22222222222222" || 
        cnpj == "33333333333333" || 
        cnpj == "44444444444444" || 
        cnpj == "55555555555555" || 
        cnpj == "66666666666666" || 
        cnpj == "77777777777777" || 
        cnpj == "88888888888888" || 
        cnpj == "99999999999999")
        return false;
         
    // Valida DVs
    tamanho = cnpj.length - 2
    numeros = cnpj.substring(0,tamanho);
    digitos = cnpj.substring(tamanho);
    soma = 0;
    pos = tamanho - 7;
    for (i = tamanho; i >= 1; i--) {
      soma += numeros.charAt(tamanho - i) * pos--;
      if (pos < 2)
            pos = 9;
    }
    resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
    if (resultado != digitos.charAt(0))
        return false;
         
    tamanho = tamanho + 1;
    numeros = cnpj.substring(0,tamanho);
    soma = 0;
    pos = tamanho - 7;
    for (i = tamanho; i >= 1; i--) {
      soma += numeros.charAt(tamanho - i) * pos--;
      if (pos < 2)
            pos = 9;
    }
    resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
    if (resultado != digitos.charAt(1))
          return false;
           
    return true;
    
}
 <input type="text" name="cnpj" id="cnpj" onkeyup="FormataCnpj(this,event)" maxlength="18"  class="form-control input-md" ng-model="cadastro.cnpj" required>

  • At what point do you want to validate? When leaving the field? In your input the only event is the Keyup that "Format CPNJ" or put the mask.

  • When leaving the field would be a good hiago, the mask is ok, what you’re getting is the validation only

  • yes, my answer worked?

  • Yes, thank you very much!

  • ae :) if you can mark as correct I thank you.

2 answers

5


Put the onblur so that when leaving the field it validates for you.

Follow the example below of how you would do in your input.

 <input type="text" name="cnpj" id="cnpj" onkeyup="FormataCnpj(this,event)" onblur="if(!validarCNPJ(this.value)){alert('CNPJ Informado é inválido'); this.value='';}" maxlength="18"  class="form-control input-md" ng-model="cadastro.cnpj" required>

-3

I made a CPF and CNPJ validator and formatter that I use in my project with Angular

export class CpfCnpjUtils {
  static isCpfValid(cpf: string): boolean {
    const cpfLength = 11;
    const weights = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
    return this.isValid(cpf, cpfLength, weights);
  }

  static isCnpjValid(cnpj: string): boolean {
    const cpfLength = 14;
    const weights = [2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5, 6];
    return this.isValid(cnpj, cpfLength, weights);
  }

  static formatCpf(cpf: string): string {
    const correctDigitsLength = 11;
    const firstDotPosition = 2;
    const secondDotPosition = 5;
    const slashPosition = -1;
    const dashPosition = 8;
    return this.format(cpf, correctDigitsLength, firstDotPosition, secondDotPosition, slashPosition, dashPosition);
  }

  static formatCnpj(cnpj: string): string {
    const correctDigitsLength = 14;
    const firstDotPosition = 1;
    const secondDotPosition = 4;
    const slashPosition = 7;
    const dashPosition = 11;
    return this.format(cnpj, correctDigitsLength, firstDotPosition, secondDotPosition, slashPosition, dashPosition);
  }

  private static format(
    digits: string,
    correctDigitsLength: number,
    firstDotPosition: number,
    secondDotPosition: number,
    slashPosition: number,
    dashPosition: number
  ): string {
    const cleanDigits = this.getOnlyNumbers(digits);
    return cleanDigits
      .slice(0, correctDigitsLength)
      .split('')
      .reduce((acc, digit, idx) => {
        const result = `${acc}${digit}`;
        if (idx !== digits.length - 1) {
          if (idx === firstDotPosition || idx === secondDotPosition) {
            return `${result}.`;
          }
          if (idx === slashPosition) {
            return `${result}/`;
          }
          if (idx === dashPosition) {
            return `${result}-`;
          }
        }
        return result;
      }, '');
  }

  private static isValid(digits: string, correctDigitsLength: number, weights: number[]): boolean {
    const cleanDigits = this.getOnlyNumbers(digits);
    if (cleanDigits.length !== correctDigitsLength || this.isAllTheSameDigits(cleanDigits)) {
      return false;
    }
    const digitsWithoutChecker = cleanDigits.substring(0, correctDigitsLength - 2);
    const digitsChecker = cleanDigits.substring(correctDigitsLength - 2, correctDigitsLength);
    const calculetedChecker = this.calcChecker(digitsWithoutChecker, weights);
    return digitsChecker === calculetedChecker;
  }

  private static getOnlyNumbers(digits: string): string {
    return digits.replace(/\D/g, '');
  }

  private static isAllTheSameDigits(digits: string): boolean {
    return !digits.split('').some((digit) => digit !== digits[0]);
  }

  private static calcChecker(digits: string, weights: number[]): string {
    const digitsLength = digits.length;
    const digitsLengthWithoutChecker = weights.length - 1;

    const sum = digits.split('').reduce((acc, digit, idx) => {
      return acc + +digit * weights[digitsLength - 1 - idx];
    }, 0);
    const sumDivisionRemainder = sum % 11;
    const checker = sumDivisionRemainder < 2 ? 0 : 11 - sumDivisionRemainder;

    if (digitsLength === digitsLengthWithoutChecker) {
      return this.calcChecker(`${digits}${checker}`, weights);
    }

    return `${digits[digitsLength - 1]}${checker}`;
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.