The main problem is that I can select Monday to Sunday, but I want to limit Tuesday, Thursday, Saturday, and Sunday to only select Monday, Wednesday, and Friday Here is the code I tried, but I don't actually know why it doesn't work:
Thanks! ! ! !
<form action="insertar_reserva_tarde.php" method="POST"> <label for="fecReserva">Día:</label> <input type="date" name="fecReserva" id="fecReserva" min="2023-06-15" max="2023-07-15"required> <br> <label for="horIniReserva">Hora de inicio:</label> <select name="horIniReserva" id="horIniReserva"> <option value="17">17:00</option> <option value="18">18:00</option> <option value="19">19:00</option> <option value="20">20:00</option> </select> <br> <label for="horFinReserva">Hora de fin:</label> <select name="horFinReserva" id="horFinReserva"> <option value="18">18:00</option> <option value="19">19:00</option> <option value="20">20:00</option> <option value="21">21:00</option> </select> <br> <input type="hidden" name="pista" value="1"> <input type="hidden" name="idHorario" value="1"> <input type="submit" value="Reservar"> </form> <?php if(isset($_POST['fecReserva'])){ $date = strtotime($_POST['fecReserva']); $dayOfWeek = date('N', $date); // obtiene el número del día de la semana (1 = lunes, 2 = martes, etc.) if($dayOfWeek == 1 || $dayOfWeek == 3 || $dayOfWeek == 5){ echo "<p>La fecha seleccionada es el ".date('d/m/Y', $date)."</p>"; } else { echo "<p>Sólo se permiten reservas en Lunes, Miércoles y Viernes.</p>"; } } ?> <script>// Everything except weekend days const validate = dateString => { const day = (new Date(dateString)).getDay(); if (day==2 || day==4 || day==6 || day==0 ) { return false; } return true; } // Sets the value to '' in case of an invalid date document.querySelector('input').onchange = evt => { if (!validate(evt.target.value)) { evt.target.value = ''; } } </script>
The purpose is to select only Monday, Wednesday and Friday
Your problem appears to be that you are attaching a listener to the input's change event and then returning false to that event.
If you only want to select odd days (based on ECMAScript day numbers), the function simply returns the result of
!!(dayNum % 2)
.The value of the input type date is a timestamp in the format YYYY-MM-DD, which will be parsed as UTC, so if you use
new Date(value)
you need to get the UTC date.The logic is illustrated below by displaying a message that intentionally cancels form submission to display success and failure without submission.
There are many other ways to achieve the same result, for example you can use valueAsDate instead of calling the Date constructor. You can also use an array of allowed or not allowed dates and test it, etc.