How to validate client-side CPF with script?

Asked

Viewed 55,577 times

20

I’m working with a CPF validation on my controller, but I need to validate when the customer leaves the input of the CPF and then return a message warning when the CPF is incorrect, through a alert or something like that.

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

Uncaught Referenceerror: validarCPF is not definedRelate: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 anything like that, or have any idea how to help me?

  • This link shows how to validate a CPF while the person is typing it http://www.tutsup.com/2014/11/17/como-validar-cpf-e-cnpj-com-javascript-ou-jquery/ . I think this is what you’re looking for

  • The script has been declared before of input?

  • @Eduardo I downloaded the project on the site, but it has an error on the line *? if ( valida_cpf_cnpj( cpf_cnpj ) {** and is not working here.

  • @Andréribeiro no, I just reversed the order of the post. The script is in JS file separately, I just joined to post.

4 answers

23


Its code does not work for many reasons, among them, when you copied the source came some tags as entities, the tags for came like this "&lt" "&gt", has a flying "j" serving as Jquery(Document.. if you want an alternative continue reading.

CPF generator and validator

To validate just use this line:

CPF.valida("123.456.789-00");

Lib already filters points and strokes.

Check 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>

<input type="text" id="input" /><span id="resposta"></span><br><br><br><br>

  • I checked this, but I need one for real-time validation, IE, as soon as the user exits the input.

  • run the script again, put an event monitoring the pressed key and the output of Focus

  • 1

    Thank you, that’s exactly what it was.

8

I adapted the response script from @Albertbitencourt.

Removing the party you consider 10 and 11 as 0, because apparently this validation does not exist.

function cpf(cpf){
    cpf = cpf.replace(/\D/g, '');
    if(cpf.toString().length != 11 || /^(\d)\1{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

How to validate and calculate the control digit of a CPF
Formula to generate Valid Cpfs

3

I set up a pseudo class in Javascript to generate and validate CPF numbers, following the rule of check digits. Source code can be found on Github:

Follow an example of use:

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

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

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

It is worth noting that the numbers generated are valid, but are not real, unless there is a collision of a random number with a real number.

To know if a number of CPF is real, only consulting the IRS, but it will be necessary to inform also the date of birth of the holder of the CPF:

  • www.receita.fazenda.gov.br/aplicacoes/atcta/Cpf/Consulta publica.Asp

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

  • www.soawebservices.com.br

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

2

I made one in javascript using the IRS algorithm.

The method takes a string without dots 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;
}
  • Various values provided by https://www.geradordecpf.org/ do not pass its algorithm :(

Browser other questions tagged

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