Registration form, check dni and if user exits PHP + AJAX

0

have if someone can guide me. I'm making a registration form, in which they have the typical fields; but the ones that I need to do verifications before inserting the registry is of Username (email) and the nif.

I have a form that when we give the submit call to an 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){
                      $("#mensaje").html(res);
                      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
                  });
          });
      });
    </script>

And then on the other hand the insertar-cliente.php

<?php include "../conexion/conexion.php" ?>
<?php
 $nif = explode('-', $_POST['nif']);
 $numeros = $partes[0];
 $letra = strtoupper($partes[1]);
   if (substr("TRWAGMYFPDXBNJZSQVHLCKE",$numeros%23,1) == $letra)
    echo '<p>El DNI: '.$nif.' es correcto!</p>';
 else
    echo '<p>La letra introducida no es corrrecta!</p>';
 exit();

$name = $_POST['name'];
$email = $_POST['email'];
$telefono = $_POST['telefono'];
$movil = $_POST['movil'];
$direccion = $_POST['direccion'];
$postal = $_POST['postal'];
$poblacion = $_POST['poblacion'];
$provincia = $_POST['provincia'];
$pass = $_POST['pass'];
$sexo = $_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)) {
   die( 'Error: ' . mysqli_error() );
 }
 mysqli_close($mysqli);
?>

What I need is to check if Username exists in the bd and if the Nif is correct.

    
asked by Miguel 06.09.2018 в 10:44
source

3 answers

0

Very good, you can do it in two ways:

1) The first is to make an ajax where you pass by parameters dni and the user and then receive it in PHP to do the corresponding consulates to see if there is something like:

"SELECT COUNT(1) FROM usuario WHERE dni = ".$dni

2) The second is to use the same ajax but make a prior consultation to the INSERT to verify if the dni exists, if it does not exist, insert it and if there is an error or a message indicating that That ID exists.

$query = "SELECT COUNT(1) existe FROM usuario WHERE dni = ".$dni;
$resultado =  mysqli_query($conn, $query);
$fila = mysqli_fetch_assoc($resultado);
$existeDNI = $fila['existe'];

if($existeDNI = 0){

 $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)) {
   die( 'Error: ' . mysqli_error() );
 }

}else{
  Aquí retornas el error al ajax
}
    
answered by 06.09.2018 в 13:39
0

Since I can not emulate the so-called Ajax, I replaced it with a promise that is resolved (or rejected) after 1.5 seconds.

I defined an object with the users:

var usuarios = {
    '665366-E': '[email protected]',
    '357911-P': '[email protected]',
    '791816-H': '[email protected]',
    '699994-N': '[email protected]',
    '427279-P': '[email protected]',
    '241585-Q': '[email protected]'
  };

So these promises check if the NIF or the mail already exists.

Basically, I check the availability with the function:

function isAvailable(nif, email) {

  return new Promise((resolve, reject) => {
    window.setTimeout(() => {
      if (Object.keys(usuarios).indexOf(nif) !== -1 ||
        Object.values(usuarios).indexOf(email) !== -1) {
        resolve({
          disponible: false
        });
      } else {
        resolve({
          disponible: true
        });
      }
    }, 1500);
  });
}

This function accepts a nif and a email . To check if a nif exists the flames as

isAvailable(nif, null) // en realidad el null es opcional

And to check an email you call it:

isAvailable(null, email)

Verification of the verification letter of the NIF can be done in the front.

 var letras = 'TRWAGMYFPDXBNJZSQVHLCKE',

 var parteNumerica = parseInt(nif.split('-')[0], 10),
    letra = nif.split('-')[1].toUpperCase(),
    letraCorrecta = letras[parteNumerica % 23];

  if (letra !== letraCorrecta) {
    label.removeClass('valid').addClass('invalid');
    label.find('small').text('letra incorrecta');
    return;
  }

When the focus of the input is removed (or the mouse exits the fieldset), the check is executed.

The send button is activated by passing the mouse over it when the two inputs are valid. When sending the check is repeated and returns false if it is not met.

The inputs are subject to a regular expression that, if not fulfilled, informs that the value entered does not conform to the expected format (if you want emails of type [email protected] that part will have to be changed.

var letras = 'TRWAGMYFPDXBNJZSQVHLCKE',
  usuarios = {
    '665366-E': '[email protected]',
    '357911-P': '[email protected]',
    '791816-H': '[email protected]',
    '699994-N': '[email protected]',
    '427279-P': '[email protected]',
    '241585-Q': '[email protected]'
  };

function isAvailable(nif, email) {

  return new Promise((resolve, reject) => {
    window.setTimeout(() => {
      if (Object.keys(usuarios).indexOf(nif) !== -1 ||
        Object.values(usuarios).indexOf(email) !== -1) {
        resolve({
          disponible: false
        });
      } else {
        resolve({
          disponible: true
        });
      }
    }, 1500);
  });
}


function checkNif() {
  var $this = $('#nif');

  $this.val($this.val().trim().toUpperCase());

  var nif = $this.val(),
    label = $this.closest('label');

  if (!/^\d{6}-[A-Z]{1}$/.test(nif)) {
    label.removeClass('valid').addClass('invalid');
    label.find('small').text('Debe ingresar 6 dígitos, un guión y una letra');
    return;
  }
  var parteNumerica = parseInt(nif.split('-')[0], 10),
    letra = nif.split('-')[1].toUpperCase(),
    letraCorrecta = letras[parteNumerica % 23];

  if (letra !== letraCorrecta) {
    label.removeClass('valid').addClass('invalid');
    label.find('small').text('letra incorrecta');
    return;
  }

  label.removeClass('invalid')
    .find('small')
    .text('Comprobando disponibilidad');

  return isAvailable(nif, null).then((response) => {
    if (response.disponible === true) {
      label.removeClass('invalid').addClass('valid');
      label.find('small').text('NIF disponible');
    } else {
      label.removeClass('valid').addClass('invalid');
      label.find('small').text('NIF ya registrado');
    }
  });

}


function checkMail() {
  var $this = $('#correo');
  $this.val($this.val().trim().toLowerCase());

  var correo = $this.val().trim(),
    label = $this.closest('label');
  if (correo === '') {
    label.removeClass('valid').addClass('invalid');
    label.find('small').text('Correo es obligatorio');
    return false;
  } else if (!/^\w+@\w+\.\w+$/.test(correo)) {
    label.removeClass('valid').addClass('invalid');
    label.find('small').text('Correo inválido');
    return false;
  }
  label.removeClass('invalid')
    .find('small')
    .text('Comprobando disponibilidad');

  return isAvailable(null, correo).then((response) => {
    if (response.disponible === true) {
      label.removeClass('invalid').addClass('valid');
      label.find('small').text('Correo disponible');
    } else {
      label.removeClass('valid').addClass('invalid');
      label.find('small').text('Correo ya registrado');
    }
  });
}


function checkSubmit() {
  var $this = $('#enviar');
  if ($('#nif').closest('label').hasClass('valid') &&
    $('#correo').closest('label').hasClass('valid')) {
    $(this).removeClass('disabled').val('Enviar');
  } else {
    $(this).addClass('disabled').val('Complete los campos para enviar');
    return false;
  }
}

jQuery('#nif').on('blur', checkNif);
jQuery('#correo').on('blur', checkMail);
jQuery('#field_nif label').on('mouseleave', checkNif);
jQuery('#field_correo label').on('mouseleave', checkMail);

jQuery('#enviar').on('click mouseover', checkSubmit);


jQuery('#formulario fieldset input').on('focus', function() {
  $(this).closest('label')
    .removeClass('invalid')
    .removeClass('valid')
    .find('small')
    .text('');
});
.invalid input {
  border: 1px solid red;
}

.valid input {
  border: 1px solid green;
}

.invalid small {
  color: red;
}

.valid small {
  color: green;
}

#formulario fieldset {
  width: 90%;
  float: left;
  clear: both;
  border-top: 0 none;
  border-left: 0 none;
  border-right: 0 none;
  border-bottom-width: 0.5px;
  border-bottom-color: #CCC;
  padding-top: 2px;
  padding-bottom: 2px;
  height: 30px;
  margin-bottom: 10px;
}

#formulario label {
  display: inline-block;
  width: 100%;
}

#formulario label span {
  display: inline-block;
  float: left;
  width: 10%;
}

#formulario input {
  float: right;
  display: inline-block;
  width: 25%;
  float: left;
}

#formulario small {
  float: left;
  display: inline-block;
  width: 60%;
  margin-left: 4%;
}

#formulario #enviar {
  width: 250px;
  cursor: not-allowed;
}

#formulario #enviar.disabled {
  color: #999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="formulario">
  <fieldset id="field_nif">
    <label for="nif">
<span>Nif:</span>
<input type="text" name="nif" id="nif" placeholder="ingrese su nif">
<small></small>
</label>
  </fieldset>
  <fieldset id="field_correo">
    <label for="nombre">
<span>Correo</span>
<input type="text" name="correo" id="correo" placeholder="ingrese su correo">
<small></small>
</label>

  </fieldset>
  <input type="submit" id="enviar" value="Complete los campos para enviar" class='disabled'>
</form>

Implementation in PHP

Your verification script user_exists.php would be something like:

<?php
$mysqli = new mysqli('localhost', 'test', 'test', 'test');

/* verificar la conexión */
if (mysqli_connect_errno()) {
    printf("Conexión fallida: %s\n", mysqli_connect_error());
    exit();
}
// capturar las entradas de POST o definirlas como '';
$nif   = isset($_POST['nif']) ? $_POST['nif'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';

$sentencia = $mysqli->prepare('SELECT nif, email FROM usuarios WHERE nif=? OR email=?');

$sentencia->bind_param('ss', $nif, $email);

/* ejecutar la consulta */
$sentencia->execute();

/* almacenar el resultado */
$sentencia->store_result();

/* contar registros que calzan */
$disponible = ($sentencia->num_rows === 0);

/* cerrar la sentencia */
$sentencia->close();

header('Content-Type: application/json');

echo json_encode(['disponible' => $disponible]);

If the query does not return records, the and email does not exist in the database. If you return records, it means that the email or the nif already exists.

The isAvailable function would change to:

function isAvailable(nif, email) {

    return jQuery.ajax({
        url: 'user_exists.php',
        method: 'POST',
        dataType: 'json',
        data: {
            nif: nif,
            email: email
        }
    });
}
    
answered by 06.09.2018 в 13:33
0

Hi !, I think the easiest way to do it is with a count, I have not given any problems in any of my projects, what the count will do is make a query to the server through php to check how many elements are in the table that you define.

Check user:

$name = $_POST['name'];
$checkuser = "SELECT COUNT(*) numero FROM Usuarios WHERE name = '$name';";

$test = $conn->query($checkuser);
$test_f = mysqli_fetch_assoc($test);

if($test_f['numero'] === "1")
   {
    echo "Este nombre de usuario ya está registrado.";
   }
 else
    {
     echo "Este nombre de usuario no está registrado, prosigue con el registro";
        }

//numero = 0: No hay usuarios registrados con ese nombre.
//numero = 1: Hay un usuario con ese nombre, no se puede completar el registro.
//numero = mas de uno: Tienes varios usuarios con el mismo nombre (con este método no debería de pasar).

To check any other data type is exactly the same process, just changing name for any other data.

For example, an email:

Check email:

$email = $_POST['email'];
$checkuser = "SELECT COUNT(*) numero FROM Usuarios WHERE name = '$email';";

$test = $conn->query($checkuser);
$test_f = mysqli_fetch_assoc($test);

if($test_f['numero'] === "1")
   {
    echo "Este nombre de usuario ya está registrado.";
   }
 else
    {
     echo "Este nombre de usuario no está registrado, prosigue con el registro";
        }

//numero = 0: No hay usuarios registrados con ese nombre.
//numero = 1: Hay un usuario con ese nombre, no se puede completar el registro.
//numero = mas de uno: Tienes varios usuarios con el mismo nombre (con este método no debería de pasar).

The DNI would follow the same process, creating a new variable $dni = $_POST['dni']; and changing the COUNT parameters.

Greetings, thanks for your question:)

    
answered by 07.09.2018 в 13:53