Using jQuery Validation Engine and CNPJ validation

Asked

Viewed 8,251 times

7

I am using the jQuery Validation Engine with this file of translations into Portuguese. I added in Javascript the following line:

"cnpj": {
    "regex": /^\d{2}\.\d{3}\.\d{3}\/\d{4}\-\d{2}$/,
     "alertText": "* CNPJ inválido"
 }

In ASPX I use:

asp:TextBox ID="txtCNPJ" runat="server" CssClass="validate[required,custom[cnpj]]

However, this validation is not very efficient, since it only checks the number of characters.

How can I make a method to validate CNPJ and continue using Validation Engine in this way?

  • What is "CNPJ " ?

  • @Sergio It is a document referring to the national register of companies here in Brazil: "Cadastro Nacional de Pessoa Jurídica". The number of each CNPJ is in question regex format and the last two are check digits.

  • @utluiz, Aha. I think I’m kind of unqualified :P But by the way, is there a pattern? order of letters (and what), numbers, points? It is based on name or generated by state?

  • @Sergio A Wikipedia has everything.

  • 1

    @utluiz boa! + 1 for Wikipédia :)

3 answers

4

Analyzing the documentation, I found funcCall[methodName], which allows calling a custom function to perform validation.

Here is an example based on the documentation:

function verificaCNPJ(field, rules, i, options){
    var valido = isCNPJValid(field.val()); //implementar a validação
    if (!valido) {
        //internacionalização
        return options.allrules.validate2fields.alertText;
    }
}

The html should look like this:

<input value="" class="validate[required,funcCall[verificaCNPJ]]" type="text" id="cnpj" name="cnpj" />

To implement the CNPJ function you can use the example from Wikipedia:

function isCNPJValid() {  
    var b = [6,5,4,3,2,9,8,7,6,5,4,3,2], c = this;
    if((c = c.replace(/[^\d]/g,"").split("")).length != 14)
        return false;
    for (var i = 0, n = 0; i < 12; n += c[i] * b[++i]); 
    if(c[12] != (((n %= 11) < 2) ? 0 : 11 - n))
        return false; 
    for (var i = 0, n = 0; i <= 12; n += c[i] * b[i++]); 
    if(c[13] != (((n %= 11) < 2) ? 0 : 11 - n))
        return false; 
    return true; 
};
  • I guess it didn’t work out so well

  • @Silvioandorinha Qual parte?

3


Follows the correct solution:

Aspx

asp:TextBox ID="txtCNPJ" runat="server" CssClass="validate[required, funcCall[validateCNPJ]]"

Put to jquery.validationEngine-pt_BR.js

"cnpj": {
          "alertText": "* CNPJ inválido"
       }

Javascript

function validateCNPJ(field, rules, i, options) {
    var valido = isCNPJValid(field.val()); //implementar a validação
    if (!valido) {
        //internacionalização
        return options.allrules.cnpj.alertText;
    }
}

function isCNPJValid(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;
}

0

  • Even if this link is a good suggestion, this answer will not be valid if one day the link fails. Also, it’s important for the community to have content right here. It would be better to include more details in your reply; Could you do that? A summary of the content of the link would help a lot! Learn more about this subject in our Community FAQ: Answers that only contain links are good?

Browser other questions tagged

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