validate cpf with javascript

-6

I have a registration page that I am validating, and now I have to validate the CPF. I got 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;
}

But now I do not know how to put it in my code. In my HTML page, I have the CPF ID field 'cpf1' and name: 'txtCPF' and in the end I have the submit 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() that serves to validate everything else. I would like to know what I should do to make this code run along with my button to register with the message: alert("CPF Inválido") only, if it is not invalid, it registers normally. I'm having trouble implementing this code in my project.

    
asked by anonymous 10.05.2018 / 20:36

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 does not let you post the entire executable HTML for several 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 VerificaCPF and verificarCPF , note that there is a difference in the spellings.

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

The ZIP and CPF fields were the wrong size maxlength .

The instruction with submit(); was in the wrong place! It should stay out of the last if .

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

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

As you can see, I also simplified the verification logic of your form a lot.

    
11.05.2018 / 05:44
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 it as validacaodenome ). She is very simple and short and does what you want.

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

I also improved the code for the verificarCPF function a bit. In it I also added if (!/[0-9]{11}/.test(strCpf)) return false; , which returns false if strCpf is not a string consisting of exactly 11 digits. This is to reject entries that are not numeric, that are very long or very short.

    
10.05.2018 / 21:50