Valid CNPJ //JavaScript Repository

Description

Checks if the brazilian CNPJ is valid.
Created: 2005.10.02

Code (Download)

//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/string/is-cnpj [rev. #1]

String.prototype.isCNPJ = function(){
    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;
};

Example (Example)

<form name="f" method="post" action="#">
    <fieldset>
    <legend>Valida??o de CNPJ</legend>
    <label>CNPJ:</label>
    <input type="text" name="cnpj" />
    <input type="submit" value="Checar" />
    </fieldset>
</form>

<script type="text/javascript">
//<![CDATA[

addEvent(document.forms.f, "submit", function(e){
    alert(this.cnpj.value.isCNPJ() ? "V?lido" : "Incorreto");
    e.preventDefault();
});

//]]>
</script>

Help

String.isCNPJ(void): Boolean
Returns true if the CNPJ is válid, otherwise, false.

Rank (Votes: 31)

4.10