// JS Calendar-Locale-Validation Tec MX // Global variables var PE_Phone_Input; var EI_Phone_Input; var currentDate = new Date(); var currentMonth = currentDate.getMonth(); var currentYear = currentDate.getFullYear(); var autofilledDate = 0; var months = [ "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre", ]; // Init document.addEventListener("DOMContentLoaded", function () { document.querySelector("form").addEventListener("submit", handleSubmit); var PE_Phone = document.querySelector("#PersonaEnlace_Phone"); var EI_Phone = document.querySelector("#Estudiante_Phone"); const estudianteInput = document.getElementById('Estudiante_Locale') const personaEnlaceInput = document.getElementById('PersonaEnlace_Locale') let estudianteLocale = String(estudianteInput.value) let personaEnlaceLocale = String(personaEnlaceInput.value) if (!estudianteLocale || estudianteLocale == '') estudianteLocale = 'mx' if (!personaEnlaceLocale || personaEnlaceLocale == '') personaEnlaceLocale = 'mx' // Initialize intlTelInput for the first input field PE_Phone_Input = window.intlTelInput(PE_Phone, { initialCountry: personaEnlaceLocale.toLowerCase(), preferredCountries: ["mx", "us"], separateDialCode: true, dropdownContainer: document.body, // Ensure dropdown appears correctly }); // Initialize intlTelInput for the second input field EI_Phone_Input = window.intlTelInput(EI_Phone, { initialCountry: estudianteLocale.toLowerCase(), preferredCountries: ["mx", "us"], separateDialCode: true, dropdownContainer: document.body, // Ensure dropdown appears correctly }); updateCalendar(); }); // Calendar functions const monthNames = [ "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" ]; let selectedDate = null; const today = new Date(); const maxYear = today.getFullYear(); let minYear = maxYear - 100; let mustBeMinor = false // $('input[name=aviso_MayoriaEdad]').change(() => { // const avisoMenorEdad = $('input[name=aviso_MayoriaEdad]:checked').val() // if (avisoMenorEdad == 'TRUE') { // minYear = maxYear - 100 // } else { // minYear = maxYear - 18 // } // }) $('#perfil').change(function () { const val = $(this).val() if (val == 'Responsable legal') { mustBeMinor = true // minYear = maxYear - 18 console.log('Dates', mustBeMinor, minYear) } else { mustBeMinor = false // minYear = maxYear - 100 console.log('Dates', mustBeMinor, minYear) } }) function toggleCalendar() { const calendar = document.getElementById('calendar'); calendar.style.display = calendar.style.display === 'none' ? 'block' : 'none'; } function updateCalendar() { const year = parseInt(document.getElementById('year').value); const month = monthNames.indexOf(document.getElementById('month').value); // Clear the input date if (autofilledDate > 1) { document.getElementById('Estudiante_FechaNacimiento').value = ''; selectedDate = null; } autofilledDate++; const calendarBody = document.getElementById('calendar-body'); calendarBody.innerHTML = ''; const firstDay = new Date(year, month, 1).getDay(); const daysInMonth = new Date(year, month + 1, 0).getDate(); let row = document.createElement('tr'); for (let i = 0; i < firstDay; i++) { const cell = document.createElement('td'); row.appendChild(cell); } for (let i = 1; i <= daysInMonth; i++) { const cell = document.createElement('td'); cell.textContent = i; cell.onclick = () => selectDate(year, month, i); const selectedFullDate = new Date(year, month, i); if (selectedFullDate >= new Date(minYear, today.getMonth(), today.getDate()) && selectedFullDate <= today) { cell.classList.add('valid-date'); } else { cell.classList.add('invalid-date'); cell.onclick = null; } row.appendChild(cell); if ((i + firstDay) % 7 === 0) { calendarBody.appendChild(row); row = document.createElement('tr'); } } calendarBody.appendChild(row); } function selectDate(year, month, day) { selectedDate = new Date(year, month, day); document.getElementById('Estudiante_FechaNacimiento').value = selectedDate.toISOString().split('T')[0]; toggleCalendar(); } function prevYear() { const yearInput = document.getElementById('year'); if (parseInt(yearInput.value) > minYear) { yearInput.value = parseInt(yearInput.value) - 1; updateCalendar(); } } function nextYear() { const yearInput = document.getElementById('year'); if (parseInt(yearInput.value) < maxYear) { yearInput.value = parseInt(yearInput.value) + 1; updateCalendar(); } } function prevMonth() { const monthInput = document.getElementById('month'); const yearInput = document.getElementById('year'); let monthIndex = monthNames.indexOf(monthInput.value); if (monthIndex === 0) { if (parseInt(yearInput.value) > minYear) { monthInput.value = monthNames[11]; yearInput.value = parseInt(yearInput.value) - 1; } } else { monthInput.value = monthNames[monthIndex - 1]; } updateCalendar(); } function nextMonth() { const monthInput = document.getElementById('month'); const yearInput = document.getElementById('year'); let monthIndex = monthNames.indexOf(monthInput.value); if (monthIndex === 11) { if (parseInt(yearInput.value) < maxYear) { monthInput.value = monthNames[0]; yearInput.value = parseInt(yearInput.value) + 1; } } else { monthInput.value = monthNames[monthIndex + 1]; } updateCalendar(); } // Initialize the calendar window.onload = () => { document.getElementById('year').value = maxYear; document.getElementById('year').setAttribute('min', minYear); document.getElementById('year').setAttribute('max', maxYear); document.getElementById('month').value = monthNames[today.getMonth()]; updateCalendar(); } // Handle submit form function function handleSubmit(e) { document.getElementById("buttonForm").disabled = true; e.preventDefault(); const formData = new FormData(e.target); for (const [k, v] of formData.entries()) { console.log(k, formData.get(k), v) } const aviso_MayoriaEdad = formData.get("aviso_MayoriaEdad"); const Estudiante_FechaNacimiento = formData.get("Estudiante_FechaNacimiento"); const perfil = formData.get("perfil"); const PersonaEnlace_FirstName = formData.get("PersonaEnlace_FirstName"); const PersonaEnlace_ApellidoPaterno = formData.get( "PersonaEnlace_ApellidoPaterno" ); const PersonaEnlace_ApellidoMaterno = formData.get( "PersonaEnlace_ApellidoMaterno" ); const PersonaEnlace_Phone = formData.get("PersonaEnlace_Phone"); const PersonaEnlace_Email = formData.get("PersonaEnlace_Email"); const Horario_Contacto = formData.get("Horario_Contacto"); const Estudiante_FirstName = formData.get("Estudiante_FirstName"); const Estudiante_ApellidoPaterno = formData.get("Estudiante_ApellidoPaterno"); const Estudiante_ApellidoMaterno = formData.get("Estudiante_ApellidoMaterno"); const Estudiante_Email = formData.get("Estudiante_Email"); const Estudiante_Phone = formData.get("Estudiante_Phone"); const Estudiante_SexoLegal = formData.get('Estudiante_SexoLegal'); const Estudiante_SexoLegalExists = $('#Estudiante_SexoLegal'); const prepatec_periodo_de_interes_pivote = formData.get( "prepatec_periodo_de_interes_pivote" ); const prepatec_prepa_de_interes_pivote = formData.get( "prepatec_prepa_de_interes_pivote" ); const area_de_interes_pivote = formData.get('area_de_interes_pivote') const prepatec_programa_de_interes_pivote = formData.get( "prepatec_programa_de_interes_pivote" ); const aviso_privacidad = formData.get("aviso_privacidad"); const comunicacion_whatsapp = formData.get("comunicacion_whatsapp"); const Estudiante_PaísProcedencia = formData.get('Estudiante_PaísProcedencia') const Estudiante_EstadoProcedencia = formData.get('Estudiante_EstadoProcedencia') const Estudiante_MunicipioProcedencia = formData.get('Estudiante_MunicipioProcedencia') const Estudiante_EscuelaProcedencia = formData.get('Estudiante_EscuelaProcedencia') //Regex const telefonoRegex = /^[0-9\s]+$/im; const correoRegex = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i; const nameRegex = /^[A-zÀ-ú\s]+$/; // Para Date() Enero = 0, Diciembre = 11 var today = new Date(); var fechaMayorEdad = new Date(); var fechaNacimientoFormatted = new Date(Estudiante_FechaNacimiento); fechaMayorEdad.setDate(today.getDate() - 6572); fechaNacimientoFormatted.setDate(fechaNacimientoFormatted.getDate() + 1); // Format Phone const countryDataPE = PE_Phone_Input.getSelectedCountryData(); const countryDataEI = EI_Phone_Input.getSelectedCountryData(); if (!aviso_MayoriaEdad) { showAlert("aviso_MayoriaEdad"); return; } if (!perfil) { showAlert("perfil"); return; } if (perfil === "Responsable legal") { if (!PersonaEnlace_FirstName.trim()) { showAlert("PersonaEnlace_FirstName"); return; } if (!nameRegex.test(PersonaEnlace_FirstName.trim())) { showAlert( "PersonaEnlace_FirstName", "Caracteres no válidos detectados. Introduce solo letras en el campo de nombre." ); return; } if (!PersonaEnlace_ApellidoPaterno.trim()) { showAlert("PersonaEnlace_ApellidoPaterno"); return; } if (!nameRegex.test(PersonaEnlace_ApellidoPaterno.trim())) { showAlert( "PersonaEnlace_ApellidoPaterno", "Caracteres no válidos detectados. Introduce solo letras en el campo de primer apellido." ); return; } if ( PersonaEnlace_ApellidoMaterno.trim() && !nameRegex.test(PersonaEnlace_ApellidoMaterno.trim()) ) { showAlert( "PersonaEnlace_ApellidoMaterno", "Caracteres no válidos detectados. Introduce solo letras en el campo de segundo apellido." ); return; } if (!telefonoRegex.test(PersonaEnlace_Phone)) { showAlert( "PersonaEnlace_Phone", "Caracteres no válidos detectados. Introduce solo números en el campo de teléfono." ); return; } if (!PE_Phone_Input.isValidNumber()) { var errorCodePE = PE_Phone_Input.getValidationError(); if ( errorCodePE === intlTelInputUtils.validationError.TOO_SHORT || errorCodePE === intlTelInputUtils.validationError.TOO_LONG ) { showAlert("PersonaEnlace_Phone", "Introduzca un teléfono celular válido"); return; } else { showAlert("PersonaEnlace_Phone", "Introduzca un teléfono celular válido"); return; } } formatPhoneNumber( "PersonaEnlace", countryDataPE.iso2, countryDataPE.dialCode ); if (PersonaEnlace_Phone == Estudiante_Phone) { showAlert("Estudiante_Phone", "Los teléfonos no pueden ser los mismos"); showAlert("PersonaEnlace_Phone", "Los teléfonos no pueden ser los mismos"); return; } if (!correoRegex.test(PersonaEnlace_Email)) { showAlert("PersonaEnlace_Email", "Introduzca un correo electrónico válido"); return; } if (PersonaEnlace_Email == Estudiante_Email) { showAlert("Estudiante_Email", "Los correos no pueden ser los mismos"); showAlert("PersonaEnlace_Email", "Los correos no pueden ser los mismos") return; } } if (!Estudiante_FirstName) { showAlert("Estudiante_FirstName"); return; } if (!nameRegex.test(Estudiante_FirstName.trim())) { showAlert( "Estudiante_FirstName", "Caracteres no válidos detectados. Introduce solo letras en el campo de nombre." ); return; } if (!Estudiante_ApellidoPaterno) { showAlert("Estudiante_ApellidoPaterno"); return; } if (!nameRegex.test(Estudiante_ApellidoPaterno.trim())) { showAlert( "Estudiante_ApellidoPaterno", "Caracteres no válidos detectados. Introduce solo letras en el campo de primer apellido." ); return; } if ( Estudiante_ApellidoMaterno.trim() && !nameRegex.test(Estudiante_ApellidoMaterno.trim()) ) { showAlert( "Estudiante_ApellidoMaterno", "Caracteres no válidos detectados. Introduce solo letras en el campo de segundo apellido." ); return; } if (!Estudiante_FechaNacimiento) { showAlert("Estudiante_FechaNacimiento", "Introduce una fecha válida"); return; } console.log('Date validation', fechaNacimientoFormatted, new Date(minYear, today.getMonth(), today.getDate())) // Verificar si el estudiante es menor o mayor de edad if (aviso_MayoriaEdad === 'TRUE') { // Si es mayor de edad, comprobar que la fecha de nacimiento sea correcta if (fechaNacimientoFormatted > new Date(today.getFullYear() - 18, today.getMonth(), today.getDate())) { showAlert("Estudiante_FechaNacimiento", "El estudiante debe ser mayor de 18 años"); return; } } else { // Si es menor de edad, comprobar que la fecha de nacimiento sea correcta if (fechaNacimientoFormatted <= new Date(today.getFullYear() - 18, today.getMonth(), today.getDate())) { showAlert("Estudiante_FechaNacimiento", "El estudiante debe ser menor de 18 años"); return; } if (fechaNacimientoFormatted > new Date(today.getFullYear() - 13, today.getMonth(), today.getDate())) { showAlert("Estudiante_FechaNacimiento", "El estudiante debe ser mayor de 13 años"); return; } } if (!Estudiante_Email) { showAlert("Estudiante_Email", "Favor de llenar este campo") return; } if (!correoRegex.test(Estudiante_Email)) { showAlert("Estudiante_Email", "Introduzca un correo electrónico válido"); return; } if (!telefonoRegex.test(Estudiante_Phone)) { showAlert( "Estudiante_Phone", "Caracteres no válidos detectados. Introduce solo números en el campo de teléfono." ); return; } if (!EI_Phone_Input.isValidNumber()) { var errorCodeEI = EI_Phone_Input.getValidationError(); if ( errorCodeEI === intlTelInputUtils.validationError.TOO_SHORT || errorCodeEI === intlTelInputUtils.validationError.TOO_LONG ) { showAlert("Estudiante_Phone", "Introduzca un teléfono celular válido"); return; } else { showAlert("Estudiante_Phone", "Introduzca un teléfono celular válido"); return; } } formatPhoneNumber("Estudiante", countryDataEI.iso2, countryDataEI.dialCode); if (Estudiante_SexoLegalExists.length > 0 && !Estudiante_SexoLegal) { showAlert('Estudiante_SexoLegal'); return; } const PaísSelect = document.querySelectorAll('#Estudiante_EscuelaProcedencia'); if (PaísSelect.length > 0) { if (!Estudiante_PaísProcedencia) { showAlert('Estudiante_PaísProcedencia'); return; } if (!Estudiante_EstadoProcedencia) { showAlert('Estudiante_EstadoProcedencia'); return; } if (!Estudiante_MunicipioProcedencia) { showAlert('Estudiante_MunicipioProcedencia'); return; } if (!Estudiante_EscuelaProcedencia) { showAlert('Estudiante_EscuelaProcedencia'); return; } } if (!Horario_Contacto) { showAlert("Horario_Contacto"); return; } if (!prepatec_periodo_de_interes_pivote) { showAlert("prepatec_periodo_de_interes_pivote"); return; } if (!prepatec_prepa_de_interes_pivote) { showAlert("prepatec_prepa_de_interes_pivote"); return; } if (!area_de_interes_pivote) { showAlert('area_de_interes_pivote') return; } if (!prepatec_programa_de_interes_pivote) { showAlert("prepatec_programa_de_interes_pivote"); return; } if (!aviso_privacidad) { showAlert("aviso_privacidad", "Debes aceptar los términos y condiciones"); return; } // if (!comunicacion_whatsapp) { // showAlert("comunicacion_whatsapp"); // return; // } e.target.submit(); // const form_container = document.querySelector(`#form-container`); // const loading_spinner = document.querySelector(`#loading-spinner`); // form_container.classList.add("d-none"); // loading_spinner.classList.remove("d-none"); } // Showalert function function showAlert(id, msg = "") { const alert = document.querySelector(`#${id}_solicitud_error`); if (msg != "") { alert.innerHTML = msg } alert.classList.remove("d-none"); alert.parentElement.parentElement.scrollIntoView({ behavior: "smooth", }); setTimeout(() => alert.classList.add("d-none"), 5000); document.getElementById("buttonForm").disabled = false; } // Format phone number function formatPhoneNumber(id, countryCode, dialCode) { const codePhone = document.querySelector(`#${id}_CodePhone`); const locale = document.querySelector(`#${id}_Locale`); codePhone.value = dialCode; locale.value = countryCode; }