I want to Create a date input that only accepts a date that comes after today, and if the user selected a date that comes before today you have to display an error message that describes that they can’t do that.
what should i add to my code :
var myForm = document.getElementById('my_form'); myForm.addEventListener('submit', function(e){ var errors = ""; var ageInput = document.getElementById('age_input'); var nameInput = document.getElementById('name_input'); if (!ageInput.value || isNaN(ageInput.value)) { ageInput.style.borderColor = 'red'; errors += 'age is invalid</br>'; } else { ageInput.style.borderColor = 'inherit'; } if(!nameInput.value) { nameInput.style.borderColor = 'red'; errors += 'name is invalidn'; } else { nameInput.style.borderColor = 'inherit'; } if (errors){ document.getElementById('errors').innerHTML = errors; // to prevent the page from reloading e.preventDefault(); } });
<form id="my_form" action="submit.php"> <label>Age: </label> <input type="text" id="age_input" /> <label>Name: </label> <input type="text" id="name_input" /> <label>date: </label> <input type="date" id="date_input" /> <button type="submit">submit</button> <p id='errors'></p> </form>
Advertisement
Answer
const datePicker = document.getElementById('date_input'); const selectedDate = new Date(datePicker.value); const today = new Date(); today.setUTCHours(0,0,0,0); if (isNaN(selectedDate) || selectedDate < today) { errors += 'you can pick dates from the past</br>'; }