How to validate CPF on client side with script?

15

I'm working with a CPF validation in my controller , but I need to validate when the client exits the input of the CPF and then return a message advising when the CPF is incorrect, alert or something similar.

I tried to do something like this, but I get an error message on the Chrome console:

  

Uncaught ReferenceError: validateCPF is not definedReport: 363 onblur

<script>
    function validarCPF() {
        if (vercpf(document.frmcpf.cpf.value))
        {
            document.frmcpf.submit();
        } else {
            errors = "1";
            if (errors)
                alert('CPF inválido');
            document.retorno = (errors == '');
        }
    }

    function vercpf(cpf) {
        if (cpf.length != 11 ||
            cpf == "00000000000" ||
            cpf == "11111111111" ||
            cpf == "22222222222" ||
            cpf == "33333333333" ||
            cpf == "44444444444" ||
            cpf == "55555555555" ||
            cpf == "66666666666" ||
            cpf == "77777777777" ||
            cpf == "88888888888" ||
            cpf == "99999999999")
            return false;

        add = 0;

        for (i = 0; i &lt; 9; i++)
                add += parseInt(cpf.charAt(i)) * (10 - i);
        rev = 11 - (add % 11);
        if (rev == 10 || rev == 11)
            rev = 0;
        if (rev != parseInt(cpf.charAt(9)))
            return false;
        add = 0;
                for (i = 0; i &lt; 10; i++)
                add += parseInt(cpf.charAt(i)) * (11 - i);
        rev = 11 - (add % 11);
        if (rev == 10 || rev == 11)
            rev = 0;
        if (rev != parseInt(cpf.charAt(10)))
            return false;
        alert('O CPF INFORMADO É VÁLIDO.');
        return true;
    }

    $j(document).ready(function () {

        $j("#meuForm").validate({
            rules: {
                NrCpf: {NrCpf: true, required: true}
            },
            messages: {
                NrCpf: {NrCpf: alert('CPF Inválido')}
            }
        });
    });
</script>

Input HTML:

<form id="meuform">
    <input type="text" data-id="NrCpf" disabled name="NrCpf" id="NrCpf" class="form-control" onblur="javascript: validarCPF(this.value);" maxlength="14">
</form>

Has anyone ever had to do something like this, or would you have any idea how to help me?

    
asked by anonymous 20.02.2015 / 01:48

4 answers

19

Your code does not work for many reasons, between them, when you copied the source came some tags as entities, the for tags came "& lt" & gt ", has a flying" j "serving Jquery (document .., if you want an alternative keep reading.

CPF Generator and Validator

To validate just use this line:

CPF.valida("123.456.789-00");

The lib already filters points and dashes.

View on Github

Example of use

/*!
*	Gerador e Validador de CPF v1.0.0
*	https://github.com/tiagoporto/gerador-validador-cpf
*	Copyright (c) 2014-2015 Tiago Porto (http://www.tiagoporto.com)
*	Released under the MIT license
*/
function CPF(){"user_strict";function r(r){for(var t=null,n=0;9>n;++n)t+=r.toString().charAt(n)*(10-n);var i=t%11;return i=2>i?0:11-i}function t(r){for(var t=null,n=0;10>n;++n)t+=r.toString().charAt(n)*(11-n);var i=t%11;return i=2>i?0:11-i}var n="CPF Inválido",i="CPF Válido";this.gera=function(){for(var n="",i=0;9>i;++i)n+=Math.floor(9*Math.random())+"";var o=r(n),a=n+"-"+o+t(n+""+o);return a},this.valida=function(o){for(var a=o.replace(/\D/g,""),u=a.substring(0,9),f=a.substring(9,11),v=0;10>v;v++)if(""+u+f==""+v+v+v+v+v+v+v+v+v+v+v)return n;var c=r(u),e=t(u+""+c);return f.toString()===c.toString()+e.toString()?i:n}}



   var CPF = new CPF();
   document.write(CPF.valida("123.456.789-00"));
   
   document.write("<br> Utilizando o proprio gerador da lib<br><br><br>");
   for(var i =0;i<40;i++) {
      var temp_cpf = CPF.gera();
      document.write(temp_cpf+" = "+CPF.valida(temp_cpf)+"<br>");
   }

$("#input").keypress(function(){
    $("#resposta").html(CPF.valida($(this).val()));
});

$("#input").blur(function(){
     $("#resposta").html(CPF.valida($(this).val()));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" id="input" /><span id="resposta"></span><br><br><br><br>
    
20.02.2015 / 02:22
3

I've assembled a JavaScript pseudo class to generate and validate CPF numbers, following the digits check rule. The source code can be found in GitHub:

Here is an example usage:

var n = new CPF().generate();

if (new CPF().validate(n)) {
  alert('sucesso!');
}

If you need to create CPF numbers for testing, I made the same algorithm available on this static site:

Note that the numbers generated are valid, but are not real, unless a random number collision with a real number occurs.

To find out if a CPF number is real, only by consulting the Internal Revenue Service, but you must also provide the CPF holder's birth date:

  • www.receita.fazenda.gov.br/aplicacoes/atcta/cpf/ConsultaPublica.asp

Finally, if there is a need for automatic validation of a large number of CPFs, I recommend the following Web Service:

  • www.soawebservices.com.br

So far it was the cheapest I found, supports HTTPS and has reasonable availability (from time to time it suffers from timeout problems).

    
23.04.2016 / 02:53
2

I did one in javascript using the federal recipe algorithm.

The method receives a string without points and dashes and returns a bool whether it is valid or not.

function VerificaCPF(strCpf) {

var soma;
var resto;
soma = 0;
if (strCpf == "00000000000") {
    return false;
}

for (i = 1; i <= 9; i++) {
    soma = soma + parseInt(strCpf.substring(i - 1, i)) * (11 - i);
}

resto = soma % 11;

if (resto == 10 || resto == 11 || resto < 2) {
    resto = 0;
} else {
    resto = 11 - resto;
}

if (resto != parseInt(strCpf.substring(9, 10))) {
    return false;
}

soma = 0;

for (i = 1; i <= 10; i++) {
    soma = soma + parseInt(strCpf.substring(i - 1, i)) * (12 - i);
}
resto = soma % 11;

if (resto == 10 || resto == 11 || resto < 2) {
    resto = 0;
} else {
    resto = 11 - resto;
}

if (resto != parseInt(strCpf.substring(10, 11))) {
    return false;
}

return true;
}
    
19.11.2015 / 19:19
2

I've adapted the response script from @AlbertBitencourt .

Removing the part that considers 10 and 11 as 0 , since apparently this validation does not exist.

function cpf(cpf){
    cpf = cpf.replace(/\D/g, '');
    if(cpf.toString().length != 11 || /^(\d){10}$/.test(cpf)) return false;
    var result = true;
    [9,10].forEach(function(j){
        var soma = 0, r;
        cpf.split(/(?=)/).splice(0,j).forEach(function(e, i){
            soma += parseInt(e) * ((j+2)-(i+1));
        });
        r = soma % 11;
        r = (r <2)?0:11-r;
        if(r != cpf.substring(j, j+1)) result = false;
    });
    return result;
}

console.log('11111111111', cpf('11111111111'));
console.log('82312321312', cpf('82312321312'));
console.log('825.566.405-02', cpf('825.566.405-02'));
console.log('875.189.681-85', cpf('875.189.681-85'));
console.log('875.189.681-86', cpf('875.189.681-86'));
console.log('640.422.216-70', cpf('640.422.216-70'));

Related Links

Validating and Calculating the Control Digit of a CPF
Formula to generate valid CPF's

    
22.01.2018 / 21:04