const formulario = document.getElementById("formulario-datos-basicos"); const notificacion = document.getElementById("mensaje-error"); obtenerNombresExamenes(); obtenerTiposIdentificacion(); obtenerRangosEdad(); function obtenerNombresExamenes(){ let url = "./controllers/CatalogosController.php?obtener=examenes"; fetch(url) .then(response => response.json()) .then(data => { const selectExamen = document.getElementById('id_examen'); let examen = new Map(); // Iterar sobre cada fila y mapear por por id_examen, nombre_examen data.forEach(row =>{ examen.set(row['id_examen'], row['nombre_examen']); }) // LLenar opciones del select de examen for (let [id_examen, nombre_examen] of examen) { selectExamen.innerHTML += ""; } }) .catch(error => console.error('Error al obtener los exámenes:', error)); } function obtenerTiposIdentificacion(){ let url = "./controllers/CatalogosController.php?obtener=identificacion"; fetch(url) .then(response => response.json()) .then(data => { const selectTipoId = document.getElementById('id_tipo_id'); let tipoId = new Map(); // Iterar sobre cada fila y mapear por por id_tipo_id, descripcion data.forEach(row =>{ tipoId.set(row['id_tipo_id'], row['descripcion']); }) // LLenar opciones del select de examen for (let [id_tipo_id, descripcion] of tipoId) { selectTipoId.innerHTML += ""; } }) .catch(error => console.error('Error al obtener los tipos de identificación:', error)); } function obtenerRangosEdad(){ let url = "./controllers/CatalogosController.php?obtener=rangosedad"; fetch(url) .then(response => response.json()) .then(data => { const selectRangoEdad = document.getElementById('id_rango_edad'); let tipoId = new Map(); // Iterar sobre cada fila y mapear por por id_tipo_id, descripcion data.forEach(row =>{ tipoId.set(row['id_rango_edad'], row['descripcion']); }) // LLenar opciones del select de examen for (let [id_rango_edad, descripcion] of tipoId) { selectRangoEdad.innerHTML += ""; } }) .catch(error => console.error('Error al obtener rangos de edad:', error)); } // Validaciones - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - function selectExamenValido(){ const selectExamen = document.getElementById('id_examen'); const idExamen = selectExamen.value; return idExamen !== "NULL"; } function selectTipoIdentificacionValido(){ const selectTipoId = document.getElementById('id_tipo_id'); const idTipoId = selectTipoId.value; return idTipoId !== "NULL"; } function selectRangoEdadValido(){ const selectRangoEdad = document.getElementById('id_rango_edad'); const idRangoEdad = selectRangoEdad.value; return idRangoEdad !== "NULL"; } function selectGeneroValido(){ const selectGenero = document.getElementById('id_genero'); const idGenero = selectGenero.value; return idGenero !== "NULL"; } // Función para validar el nombre function validarNombre(nombre) { const nombreRegex = /^[a-zA-ZÀ-ÿ\s]+$/; // Permite letras y espacios return nombreRegex.test(nombre); } //funcion para validar apellido function validarApellido(apellido) { const apellidoRegex = /^[a-zA-ZÀ-ÿ]+$/; // Permite solo letras, sin espacios return apellidoRegex.test(apellido); } // Función para validar número telefónico (10 dígitos) function validarTelefono(telefono) { const telefonoRegex = /^\d{10}$/; return telefonoRegex.test(telefono); } // Función para validar correo electrónico function validarCorreo(correo) { const correoRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; return correoRegex.test(correo); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Validaciones formulario.addEventListener("submit", async(event) => { event.preventDefault(); // Limpiar mensaje de error previo notificacion.textContent = ""; notificacion.style.display = "none"; // Obtener valores de los campos const idCandidato = document.getElementById('id_candidato').value; const fechaEntrada = document.getElementById('fecha_entrada').value; const fechaSalida = document.getElementById('fecha_salida').value; const nombres = document.getElementById('nombres').value.trim(); const primerApellido = document.getElementById('primer_apellido').value.trim(); const segundoApellido = document.getElementById('segundo_apellido').value.trim(); const correo = document.getElementById('correo').value.trim(); const telefono = document.getElementById('telefono').value.trim(); const idExamen = document.getElementById('id_examen').value; const idTipoId = document.getElementById('id_tipo_id').value; const idRangoEdad = document.getElementById('id_rango_edad').value; const idGenero = document.getElementById('id_genero').value; // Validaciones let errores = []; // Validar correo electrónico if (!validarCorreo(correo)) { errores.push("El correo electrónico no es válido. "); } // validar nombre if (!validarNombre(nombres)) { errores.push("El nombre no tiene un formato válido. "); } // validar apellido if (!validarApellido(primerApellido)) { errores.push("El primer apellido no tiene un formato válido. "); } if (!validarApellido(segundoApellido)) { errores.push("El segundo apellido no tiene un formato válido. "); } // Validar número telefónico if (!validarTelefono(telefono)) { errores.push("El número telefónico debe ser un número de 10 dígitos. "); } if(!selectExamenValido()){ errores.push("Seleccione un examen. "); } if(!selectTipoIdentificacionValido()){ errores.push("Seleccione un tipo de identificación. "); } if(!selectRangoEdadValido()){ errores.push("Seleccione un rango de edad. "); } if(!selectGeneroValido()){ errores.push("Seleccione un género. "); } // Si hay errores, mostrarlos y detener el envío if (errores.length > 0) { notificacion.textContent = errores.join("\n"); notificacion.style.display = "block"; return; } // Preparar datos para envío const formData = new FormData(); //formData.append("fecha_entrada", fechaEntrada); // No se usa porque tiene valor default //formData.append("fecha_salida", fechaSalida); // Se llena al completar el otro formulario de información formData.append("nombres", nombres); formData.append("primer_apellido", primerApellido); formData.append("segundo_apellido", segundoApellido); formData.append("correo", correo); formData.append("telefono", telefono); formData.append("id_examen", idExamen); formData.append("id_tipo_id", idTipoId); formData.append("id_rango_edad", idRangoEdad); formData.append("id_genero", idGenero); // Enviar petición POST para registrar candidato try { const respuesta = await fetch('controllers/registrarCandidato.php', { method: "POST", body: formData, }); // Obtener respuesta de petición de registro const resultado = await respuesta.json(); // Verificar si el registro fue exitoso if (resultado.registroExitoso) { alert('Se guardó la información correctamente'); window.location.href = 'inicio.html'; } else { notificacion.textContent = resultado.message; notificacion.style.display = "block"; } } catch (error) { notificacion.textContent = "Lo sentimos, ocurrió un error: " + error.message; notificacion.style.display = "block"; } });