validate Cpf with javascript

Asked

Viewed 4,931 times

-5

I have a registration page that I am validating, and now I have to validate the CPF. I took a code here on the site to validate it, this:

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;
}

Only now I don’t know how to put it in my code. On my HTML page, I have the CPF field of ID 'cpf1' and name: 'txtCPF' and at the end I have the sign-up button of type 'Submit' name='btn1' onclick='return validacaodenome() (which is my function that I use to validate everything else except the CPF.

And on my script page I have a function validacaodenome() which serves to validate everything else. I would like to know what I must do to make this code run along with my sign up button with the message: alert("CPF Inválido") only, if not invalid, he registers normally. I’m having trouble implementing this code in my project.

  • has a Function in jquery that does this friend check

  • your doubt is like calling?

  • There is already a question (with answer) to guide you: https://answall.com/questions/51340/comorvalidar-cpf-no-lado-do-cliente-com-script

  • @Laerte yes, I’m doubting how to call it

2 answers

0


Try this here:

function muitoCurto(campo, nome, tamanho) {
    if (campo.value.length >= tamanho) return false;
    alert("O conteúdo do campo '" + nome
            + "' deveria ter pelo menos " + tamanho + " caracteres."
            + " Por favor, preencha-o corretamente.");
    return true;
}

function tamanhoErrado(campo, nome, tamanho) {
    if (campo.value.length === tamanho) return false;
    alert("O conteúdo do campo '" + nome
            + "' deveria ter exatamente " + tamanho + " caracteres. "
            + "Por favor, preencha-o corretamente.");
    return true;
}

function naoNumerico(campo, nome) {
    if (!isNaN(campo.value)) return false;
    alert("Digite somente números no campo '" + nome + "', por favor.");
    return true;
}

function diferentes(campo1, nome1, campo2, nome2) {
    if (campo1.value === campo2.value) return false;
    alert("Os campos '" + nome1 + "' e '" + nome2 + "' devem ser iguais.");
    return true;
}

function validarFormulario() {
    var cad = document.getElementById('cad');

    if (muitoCurto(cad.txtnome, 'Nome', 2)) return;
    if (muitoCurto(cad.txtsobrenome, 'Sobrenome', 2)) return;
    if (tamanhoErrado(cad.txtCPF, 'CPF', 11)) return;
    if (tamanhoErrado(cad.txtDDD, 'DDD', 2)) return;
    if (muitoCurto(cad.txtContato, 'Nº do telefone', 8)) return;
    if (muitoCurto(cad.txtEmail1, 'E-mail', 10)) return;
    if (muitoCurto(cad.txtRua, 'Logradouro', 3)) return;
    if (muitoCurto(cad.txtBairro, 'Bairro', 3)) return;
    if (muitoCurto(cad.txtCidade, 'Cidade', 3)) return;
    if (muitoCurto(cad.txtNumero, 'Número do endereço', 1)) return;
    if (tamanhoErrado(cad.txtCep, 'CEP', 8)) return;
    if (muitoCurto(cad.txtLogin, 'Nome de usuário', 7)) return;
    if (muitoCurto(cad.txtsenha, 'Senha', 6)) return;
    if (muitoCurto(cad.txtCsenha, 'Confirmação da senha', 6)) return;
    if (naoNumerico(cad.txtCPF, 'CPF')) return;
    if (naoNumerico(cad.txtDDD, 'DDD')) return;
    if (naoNumerico(cad.txtContato, 'Nº do telefone')) return;
    //if (naoNumerico(cad.txtNumero, 'Número')) return;
    if (naoNumerico(cad.txtCep, 'CEP')) return;

    if (diferentes(cad.txtsenha, 'Senha', cad.txtCsenha, 'Confirmação da Senha')) return;
    if (diferentes(cad.txtEmail1, 'E-mail', cad.txtEmail2, 'Confirmação de E-mail')) return;

    if (cad.txtdata_nasc.value.length !== 10) {
        alert("Formato de 'data de nascimento' inválido."
                + " Por favor, preencha-o corretamente.");
        return;
    }

    if (!verificarCPF(cad.txtCPF.value)) {
        alert("Os dígitos verificadores do CPF não conferem.");
        return;  
    }

    cad.submit();
}

function verificarCPF(strCpf) {
    if (!/[0-9]{11}/.test(strCpf)) return false;
    if (strCpf === "00000000000") return false;

    var soma = 0;

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

    var 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 (var i = 1; i <= 10; i++) {
        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;
}
<form id="cad" method="post" action="#" required>
    <h3>Dados pessoais</h3>
    Nome: <input type="text" name="txtnome" maxlength="40" required />
    <br>
    Sobrenome: <input type="text" name="txtsobrenome" maxlength="30" required />
    <br>
    Data de nascimento: <input type="date" name="txtdata_nasc" required />
    <br>
    CPF: <input type="text" id="cpf1" name="txtCPF" maxlength="11" required />
    <br>

    <h3>Dados para Contato</h3>
    DDD: <input type="text" name="txtDDD" placeholder="Ex: (###)"  maxlength="2" required /><br>
    Tipo: <input type="radio" name="rbT" value="Celular" checked />Celular
    <input type="radio" name="rbT" value="Telefone" />Telefone
    <br>  
    Nº: <input type="tel" name="txtContato" maxlength="9" required  />
    <br>  
    E-mail: <input type="email" name="txtEmail1" maxlength="50" id="Email1" placeholder="[email protected]" required />
    <br>
    Confirmação de E-mail: <input type="email" name="txtEmail2" maxlength="50" id="Email2" required />
    <br>

    <h3>Dados do Endereço</h3>
    Logradouro: <input type="text" name="txtRua" maxlength="50" required />
    <br>
    Bairro: <input type="text" name="txtBairro" maxlength="35" required />
    <br>
    Cidade: <input type="text" name="txtCidade" maxlength="25" required />
    <br>
    Estado:
    <select name="cbEstado" required>
        <option>Acre</option>    
        <option>Alagoas</option>
        <option>Amapá</option>
        <option>Amazonas</option>
        <option>Bahia</option>
        <option>Brasília</option>
        <option>Ceará</option>
        <option>Espírito Santo</option>
        <option>Goiás</option>
        <option>Maranhão</option>
        <option>Mato Grosso</option>
        <option>Mato Grosso do Sul</option>
        <option>Minas Gerais</option>
        <option>Pará</option>
        <option>Paraíba</option>
        <option>Paraná</option>
        <option>Pernambuco</option>
        <option>Piauí</option>
        <option>Rio de Janeiro</option>
        <option>Rio Grande do Norte</option>
        <option>Rio Grande do Sul</option>
        <option>Rondônia</option>
        <option>Roraima</option>
        <option>Santa Catarina</option>
        <option>São Paulo</option>
        <option>Sergipe</option>
        <option>Tocantins</option>
    </select>
    <br>
    Número: <input type="text" name="txtNumero" maxlength="7" required />
    <br>
    CEP: <input type="text" name="txtCep" placeholder="Ex: #####-###" maxlength="8" required />
    <br>
    Complemento: <input type="text" name="txtComplemento" maxlength="40" />
    <br>

    <h3>Dados da conta</h3>
    Nome de usuário: <input type="text" name="txtLogin" required maxlength="20" />
    <br>
    Senha: <input type="password" name="txtsenha" required maxlength="20" />
    <br>
    Confirmação da senha: <input type="password" name="txtCsenha" required maxlength="20" />
    <br>
    Tipo de usuário: <input type="radio" name="rb" value="Usuario" checked />Cliente
    <input type="radio" name="rb" value="Tecnico" />Técnico
    <br>

    <button type="button" id="btn1" onclick='javascript: validarFormulario()'>Cadastrar</button>
</form>

Stackoverflow doesn’t let you post the entire executable HTML due to various reasons. So, the ideal HTML structure would be this:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Cadastro</title>
        <script type="text/javascript" src="javascrito.js"></script>
    </head>
    <body>
    <!--
        COPIE E COLE O HTML ACIMA AQUI!
    -->
    </body>
</html>

There were some errors in your code, such as using VerificaCPF and verificarCPF, note that there are differences in spellings.

There were also two buttons defined in different ways, which ended up confusing and none of them were right, one was half right and half wrong and the other was half right and the other half wrong.

The CEP and CPF fields were the size of the maxlength wrong.

The instruction with the submit(); was in the wrong place! She was supposed to stay out of the last if.

Note that street numbers are not necessarily numerical. For example, in 2015, I lived at 3524A and my neighbor was 3524B. In addition, unnumbered streets are often represented with "s/n".

There are names and surnames with two letters, including personally know two people, descendants of Chinese, with the surname "Li". I’ve seen the first name only have two letters too.

As you can see, I have also greatly simplified the verification logic of your form.

  • really dude, I don’t know what words I can thank you with, you just saved my life and my TCC work, thank you so much, from your code I learned many things.

  • There’s only one problem, not that I’m complaining, but the CPF checker remains the same, if I type a CPF number it always comes back with the error message set as Alert("CPF checkers do not match.");

  • Victor, I’m sorry if it’s too much to ask, but could you take a look again?

  • it only makes no mistake if I type any number of up to 11 characters but it ends with a '0' (zero) at the end. However, if I type such number, example '12345678910' and press the sign up button, it does not return any error, but does not send the form, remains the same.

  • In fact, I don’t understand anything. Some Cpf he leaves register and others he returns with the error

  • @sdkamda2323 I just tested with '12345678910' and it gave the message "The CPF checker digits do not match." I tested using this blue "Run" button on top. To generate random CPF numbers that are valid, use this site.

  • Ahhh, so I was the one who was wrong. I get it. Thank you ^^

  • I managed to find the code, thanks <3

  • thanks to you, now I can solve other problems on my registration page, which before could not because my code was disorganized. Thank you very much, from my heart.

Show 4 more comments

0

function verificarCPF(strCpf) {
    if (!/[0-9]{11}/.test(strCpf)) return false;
    if (strCpf === "00000000000") return false;

    var soma = 0;

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

    var 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 (var i = 1; i <= 10; i++) {
        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;
}

function validarNome() {
    var strCpf = document.getElementById('cpf1').value;
    if (!verificarCPF(strCpf)) {
        alert("CPF inválido");
        return;
    }
    document.getElementById('frm').submit();
}
<form id="frm" method="POST" action="example.com/">
    <div>Nome: <input type="text" id="nome" name="txtNome" value="Zé" /></div>
    <div>CPF: <input type="text" id="cpf1" name="txtCPF" value="00000000000" /> (sem pontos, traços e nem espaços em branco)</div>
    <div><button type="button" id="btn1" onclick='javascript:validarNome()'>Enviar</button></div>
</form>

See in the code above the function validarNome (I think it’s best to call her that validacaodenome). She’s very simple and short and does what you want.

Click on the blue button Execute to test this code. If the CPF is invalid, it gives you the alert. If valid, it gives the Submit in the form (but the result of Submit is a 404 error because it does not send the data somewhere that actually exists).

Also improved a little function code verificarCPF. In it I also added the if (!/[0-9]{11}/.test(strCpf)) return false;, that brings back false if the strCpf is not a string composed of exactly 11 digits. This serves to reject entries that are not numerical, that are very long or very short.

  • @sdkamda2323 I posted another answer below to leave more organized, because it is already quite different than the one I originally posted here.

Browser other questions tagged

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