How do I validate Cpf for my database values?

Asked

Viewed 1,168 times

1

I have the code below, which accepts values in your inputs and then sends them to the database.
I want that when the user clicks submit, if Cpf is invalid (EX:111.111.111-11), it does not send any value to the database and shows an Alert on the screen indicating that nothing has been added, need an if that has as a condition the valid Cpf, only if the Cpf is valid the values will be sent

Here we have the inputs

	<form action="Dados.php"  method="POST" >
			<table class="table table-striped">
			<thead>
			<tr>
				<th>Nome</th>
				<th>Cpf</th>
				<th>Cep</th>
				<th>Rua</th>
				<th>Bairro</th>
				<th>Cidade</th>
				<th>Estado</th>
				<th>Ibge</th>
				</tr>			
			</thead>
			
			<tbody>
			<tr>
				<td><input type="text" class="form-control input-sm" name="nom" required><br></td>
				
				<td><input type="text" class="form-control input-sm" id="cpf"  name="cpf" required><br></td>
				
				<td><input type="text" class="form-control input-sm" id="cep" name="end" required><br></td>
				
        		<td><input name="rua" class="form-control input-sm" type="text" id="rua" required /><br /></td>
        		
        		<td><input name="bairro" class="form-control input-sm" type="text" id="bairro" required/><br /></td>
        		
        		<td><input name="cidade" class="form-control input-sm" type="text" id="cidade" required/><br /></td>
        		
        		<td><input name="uf" class="form-control input-sm" type="text" id="uf" required/><br /></td>
        	
        		<td><input name="ibge" class="form-control input-sm" type="text" id="ibge" required/><br /></td>
				
			</tr>
			</tbody>
			</table>
			<input type="submit" value="Criar Registro" onclick="function validaCPF()" class="btn btn-default"><input type="button" class="btn btn-warning" value="Voltar"
onclick="window.location='/Banco_de_dados/index.php';"/>
			</form>

And here we have the code that sends the values to the bank

<body>
<?php
//declarando variaveis//
    $servername = 'localhost';
    $username = 'root';
    $password = '';
    $dbname = 'meubd';
    $nome = $_POST['nom'];
    $cpf = $_POST['cpf'];
    $cep = $_POST['end'];
    $rua = $_POST['rua'];
    $bairro = $_POST['bairro'];
    $cidade = $_POST['cidade'];
    $uf = $_POST['uf'];
    $ibge = $_POST['ibge'];
    function validaCPF($cpf = null) {

        // Verifica se um número foi informado
        if(empty($cpf)) {
            return false;
            echo "Cpf";
        }

        // Elimina possivel mascara
        $cpf = ereg_replace('[^0-9]', '', $cpf);
        $cpf = str_pad($cpf, 11, '0', STR_PAD_LEFT);

        // Verifica se o numero de digitos informados é igual a 11
        if (strlen($cpf) != 11) {
            return false;
        }
        // Verifica se nenhuma das sequências invalidas abaixo
        // foi digitada. Caso afirmativo, retorna falso
        else if ($cpf == '00000000000' ||
                $cpf == '11111111111' ||
                $cpf == '22222222222' ||
                $cpf == '33333333333' ||
                $cpf == '44444444444' ||
                $cpf == '55555555555' ||
                $cpf == '66666666666' ||
                $cpf == '77777777777' ||
                $cpf == '88888888888' ||
                $cpf == '99999999999') {
                    return false;
                    // Calcula os digitos verificadores para verificar se o
                    // CPF é válido
                } else {

                    for ($t = 9; $t < 11; $t++) {

                        for ($d = 0, $c = 0; $c < $t; $c++) {
                            $d += $cpf{$c} * (($t + 1) - $c);
                        }
                        $d = ((10 * $d) % 11) % 10;
                        if ($cpf{$c} != $d) {
                            return false;
                        }
                    }

                    return true;
                    $sql = 'INSERT INTO pessoas VALUES ("'.$nome.'", "'.$cpf.'", "'.$cep.'" , "'.$rua.'", "'.$bairro.'", "'.$cidade.'", "'.$uf.'", "'.$ibge.'")';
                    //verificando se os valores foram inseridos//
                    if ($conn->query($sql) === TRUE) {
                        echo "<br>Os valores foram adicionados corretamente";
                    } else {
                        echo "<br>Error: " . $sql . "<br>" . $conn->error;

                    }

                }
    }

//conectando ao banco de dados//verificando conexão//
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        die("Conecxão Falhou: " . $conn->connect_error);
    }

    echo "Conexao foi um sucesso";


//fechando conexão//
    $conn ->close();
?>
</body>

As I mentioned before, there may be many errors in my code, so I ask for your help.

  • There is an API ready for this type of validations, just import from Maven, follow the [link][1] [1]: https://github.com/jereztech/validation-br-api

2 answers

1


The only way to ensure that a CPF is valid is by checking its checker digits. A CPF is formed as follows: XXX.XXX.XXX-DD. "X" are the base numbers and "DD" are the check digits of the "X".

The calculation of these two digit checkers is done through the Module 11

To understand how it works:

More information about Module 11 you can find here

Below a code in Java (not very explanatory) but that takes a String (of numbers) and returns the Module 11 of this value.

public Integer getDVModulo11(String valor){
    StringBuilder valorFiltrado = new StringBuilder().append(valor);
    Integer indiceMultiplicacao = 2;
    Integer soma = 0;
    //1º PASSO
    for (Integer i = valorFiltrado.length()-1; i > -1; i--) {
        Integer numero = Character.getNumericValue(valorFiltrado.toString().charAt(i));
        Integer multiplicacao = (numero * indiceMultiplicacao);
        //2º PASSO
        soma = soma + multiplicacao;
        if(indiceMultiplicacao < 9) {
            indiceMultiplicacao++;
        }else{
            indiceMultiplicacao = 2;
        }
    }
    //3º PASSO
    Integer resultado = soma % 11;
    //4º PASSO
    resultado = 11 - resultado;
    if(resultado > 9){
        return 0;
    }else{
        return resultado;
    }
}
  • Thanks for the code, but the problem I’m really having is that when I type my Cpf and it goes through the function for more than false it sends the value to the database, it can help me with that?

  • I don’t know if there are these problems in PHP, but in java when comparing String you don’t use "==" but . equals(), maybe that’s the problem. Ex.: $Cpf == '88888888888'.

  • Because then, this is the same code used by the IRS, it was supposed to work, but that’s not the problem, what I can’t do is put the code to do a check where if Cpf is valid adds data in the table and if nothing happens. What do I do?

  • The validaCPF function has more things than validating a Cpf in its code. Do a function that aims to actually only check if Cpf is valid and then create a function that only adds in the database with an if in the validaCPF function, if the validaCPF returns true it adds, otherwise it does not add.

  • I managed to get him to send the data, I did as you said in the comment and it worked perfectly so I will mark your response as right

0

You could check the CPF informed by the client with a JS function.

Would look like this:

    <script>
 function validaCPF(cpf)
  {
    var numeros, digitos, soma, i, resultado, digitos_iguais;
    digitos_iguais = 1;
    if (cpf.length < 11)
          return false;
    for (i = 0; i < cpf.length - 1; i++)
          if (cpf.charAt(i) != cpf.charAt(i + 1))
                {
                digitos_iguais = 0;
                break;
                }
    if (!digitos_iguais)
          {
          numeros = cpf.substring(0,9);
          digitos = cpf.substring(9);
          soma = 0;
          for (i = 10; i > 1; i--)
                soma += numeros.charAt(10 - i) * i;
          resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
          if (resultado != digitos.charAt(0))
                return false;
          numeros = cpf.substring(0,10);
          soma = 0;
          for (i = 11; i > 1; i--)
                soma += numeros.charAt(11 - i) * i;
          resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
          if (resultado != digitos.charAt(1))
                return false;
          return true;
          }
    else
        return false;
  }
    </script>

Following test: https://jsfiddle.net/jzvtcLxq/

Browser other questions tagged

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