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