<script>
document.addEventListener('DOMContentLoaded', function() {
const campo = document.querySelector('input[name="Nif"]');
if (!campo) return;
function validarDocumento(valor) {
valor = valor.toUpperCase().replace(/[\s-]/g, '');
const letras = 'TRWAGMYFPDXBNJZSQVHLCKE';
// DNI
if (/^\d{8}[A-Z]$/.test(valor)) {
const numero = valor.substring(0, 8);
const letra = valor.substring(8);
return letras[numero % 23] === letra;
}
// NIE
if (/^[XYZ]\d{7}[A-Z]$/.test(valor)) {
let numero = valor.substring(0, 8)
.replace('X', '0')
.replace('Y', '1')
.replace('Z', '2');
const letra = valor.substring(8);
return letras[numero % 23] === letra;
}
return false;
}
function mostrarError() {
let error = campo.parentNode.querySelector('.dni-error');
if (!error) {
error = document.createElement('span');
error.className = 'dni-error';
error.style.color = '#dc3545';
error.style.display = 'block';
error.style.marginTop = '5px';
campo.parentNode.appendChild(error);
}
const valor = campo.value.trim();
if (valor === '') {
error.remove();
return;
}
if (validarDocumento(valor)) {
error.remove();
} else {
error.textContent = 'El DNI/NIE introducido no es válido.';
}
}
campo.addEventListener('blur', mostrarError);
campo.addEventListener('input', mostrarError);
});
</script>