Validate a DNI - NIF in PHP

1

Continuing with the registration of clients, I have to validate if the DNI or NIF exists, and I would like to know if it can be verified if the DNI or NIF is correct. I would also like the fact that in the input I put a mask with the fields that have to be and do not get out of there. I show what I have now:

input del dni nif

<div class="col-5">
  <label class="inputReg">NIF/DNI</label>
    <div class="form-group" style="margin-bottom: 28px;">
     <input type="text" class=" my-form-control" id="nif" name="nif" placeholder="nif/dni" required />
    </div>
</div> 

Here the AJAX

<script>
      $(function(){
          $("#formuploadajax1").on("submit", function(e){
              e.preventDefault();
              var f = $(this);
              var formData = new FormData(document.getElementById("formuploadajax1"));
              formData.append("dato", "valor");
              //formData.append(f.attr("name"), $(this)[0].files[0]);
              $.ajax({
                  url: "incluCuenta/insertar-cliente.php",
                  type: "post",
                  dataType: "html",
                  data: formData,
                  cache: false,
                  contentType: false,
                  processData: false
              })
                  .done(function(res){
                    if(res=="1"){
                        toastr["info"]("Registro exitoso!", "Mensaje")
                             setTimeout(function () {
                             window.location.href = "login.php"; //will redirect to your blog page (an ex: blog.html)
                         }, 1500); //will call the function after 2 secs
                    }else{
                        $("#mensaje").html(res);
                        toastr["error"]("Utiliza otro usuario!", "Mensaje")
                    }
                  });
          });
      });
    </script>

Here the insertar-cliente.php

<?php
    include "../conexion/conexion.php";

    mysqli_set_charset($mysqli, "utf8");
    $results = 'SELECT * FROM Usuarios';
    $rec = mysqli_query($mysqli, $results);

    if ($rec === false) {
    die('ERROR SQL: ' . htmlspecialchars(mysqli_error($mysqli)));
    }
    while ($results = mysqli_fetch_object($rec)) {

    if(mb_strtolower($results->Username) == mb_strtolower($_POST['email'])) {

    die('<div class=\'form\'> 
        <div class="alert alert-danger" style="font-size: 14px;"><strong>¡Error!</strong> Este usuario ya esta en uso.</div>

    </div>');
    }
 }

$name = mysqli_real_escape_string($mysqli, $_POST['name']);
$email = mysqli_real_escape_string($mysqli, $_POST['email']);
$telefono = mysqli_real_escape_string($mysqli, $_POST['telefono']);
$movil = mysqli_real_escape_string($mysqli, $_POST['movil']);
$nif = mysqli_real_escape_string($mysqli, $_POST['nif']);
$direccion = mysqli_real_escape_string($mysqli, $_POST['direccion']);
$postal = mysqli_real_escape_string($mysqli, $_POST['postal']);
$poblacion = mysqli_real_escape_string($mysqli, $_POST['poblacion']);
$provincia = mysqli_real_escape_string($mysqli, $_POST['provincia']);
$pass = mysqli_real_escape_string($mysqli, $_POST['pass']);
$sexo = mysqli_real_escape_string($mysqli, $_POST['sexo']);

$fecha = date('y,m,d');

$results = "
 INSERT INTO Usuarios (
    Fecha,
    Sexo,
    Nombre,
    Password,
    Username,
    Direccion,
    Postal,
    Poblacion,
    Provincia,
    Telefono,
    Movil,
    Dni,
    intestado
 ) VALUES (
    '$fecha',
    '$sexo',
    '$name',
    '$pass',
    '$email',
    '$direccion',
    '$postal',
    '$poblacion',
    '$provincia',
    '$telefono',
    '$movil',
    '$nif',
    '1'
 )
";
if (mysqli_query($mysqli, $results) === false) {
/* Aquí olvidaste poner como primer parámetro la conexión mysqli */
die('Error SQL: ' . htmlspecialchars(mysqli_error($mysqli)));
}

echo "1";
    
asked by Miguel 07.09.2018 в 12:06
source

1 answer

0

To check if the DNI is repeated you can add the check in the while loop:

<?php
/* ... */
while ($results = mysqli_fetch_object($rec)) {
    if (mb_strtolower($results->Username) == mb_strtolower($_POST['email'])) {
        die('<div class=\'form\'> 
        <div class="alert alert-danger" style="font-size: 14px;"><strong>¡Error!</strong> Este usuario ya esta en uso.</div>
    </div>');
    }
    if (mb_strtolower($results->Dni) == mb_strtolower($_POST['nif'])) {
        die('<div class=\'form\'> 
        <div class="alert alert-danger" style="font-size: 14px;"><strong>¡Error!</strong> Este DNI ya está en uso.</div>
    </div>');
    }
}

But I recommend you check previously that its format is correct in both Javascript and PHP:

Javascript

function comprobar_nif(dni) {
    if (dni.length != 9) {
        return false;
    }
    /* Ajustamos las letras especiales "x", "y" y "z" */
    switch(dni.charAt(0).toLowerCase()) {
        case 'x':
            dni = '0' + dni.substr(1);
            break;
        case 'y':
            dni = '1' + dni.substr(1);
            break;
        case 'z':
            dni = '2' + dni.substr(1);
            break;
        }
    numero = parseInt(dni.substr(0, dni.length - 1)) % 23;
    letra = dni.substr(dni.length - 1, 1);
    return letra != 'TRWAGMYFPDXBNJZSQVHLCKET'.substring(numero, numero + 1);
}

Adding the check:

$("#formuploadajax1").on("submit", function(e){
    e.preventDefault();
    if (comprobar_nif($('#nif').val()) == false) {
        alert('El DNI está mal');
        return;
    }
    /* ... */

PHP

<?php
function comprobar_nif($dni) {
    if (strlen($dni) != 9) {
        return false;
    }
    /* Ajustamos las letras especiales "x", "y" y "z" */
    switch(strtolower(substr($dni, 0, 1))) {
        case 'x':
            $dni = '0' + substr($dni, 1);
            break;
        case 'y':
            $dni = '1' + substr($dni, 1);
            break;
        case 'z':
            $dni = '2' + substr($dni, 1);
            break;
        }
    $numero = intval(substr($dni, 0, strlen($dni) - 1)) % 23;
    $letra = substr($dni, strlen($dni) - 1);
    return $letra == substr('TRWAGMYFPDXBNJZSQVHLCKET', $numero, 1);
}
/* Comprobamos si el DNI enviado por el formulario es válido */
if (comprobar_nif($_POST['nif']) === false) {
    die('<div class=\'form\'> 
    <div class="alert alert-danger" style="font-size: 14px;"><strong>¡Error!</strong> Este DNI no es válido.</div>
</div>');
}
    
answered by 07.09.2018 / 12:34
source