Valid CPF //JavaScript Repository

Description

Checks if the brazilian CPF is valid.
Created: 2005.10.02

Code (Download)

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

String.prototype.isCPF = function(){
    var c = this;
    if((c = c.replace(/[^\d]/g,"").split("")).length != 11) return false;
    if(new RegExp("^" + c[0] + "{11}$").test(c.join(""))) return false;
    for(var s = 10, n = 0, i = 0; s >= 2; n += c[i++] * s--);
    if(c[9] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
    for(var s = 11, n = 0, i = 0; s >= 2; n += c[i++] * s--);
    if(c[10] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
    return true;
};

Example (Example)

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

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

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

//]]>
</script>

Help

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

Rank (Votes: 73)

3.95