i want to Check if The End Date Is Bigger Than The Start Date , i had add an HTML Code to Get the Date Entered, and also i have wrote this Script to Check the if the End Date is bigger Than the Start Date.
// Function to check if the DateFin is Bigger Than The DateDebut
document.getElementById('DateFin').addEventListener('change', function() {
var dateDebut = document.getElementById('DateFin').value.trim();
var dateFin = document.getElementById('DateFin').value.trim();
if (isNaN(dateFin) || dateFin < dateDebut) {
document.getElementById('error-message').innerText = "The End Date must be greater than or equal to the Start Date";
document.getElementById('DateDebut').value = "";
document.getElementById('DateFin').value = "";
} else {
document.getElementById('error-message').innerText = "";
}
});
<div class="mb-3">
<label for="datadebut" class="form-label text_color">Date de Début :</label>
<input type="date" class="text_color btn_designBtn bold-border-label form-control" id="DateDebut" name="searchDateDebut" value="{{ $searchDateDebut ?? '' }}">
<div></div>
</div>
<div class="mb-3">
<label for="datafin" class="form-label text_color">Date de Fin :</label>
<input type="text" class="text_color btn_designBtn bold-border-label form-control" id="DateFin" name="searchDateFin" placeholder="jj/mm/yyyy">
<div id="error-message" style="color: red;"></div>
</div>
But When i try the write the full End Date the Script is executed directly whiout a finish write the year example : i try to write the : startDate = 15/01/2024
and when i write the endDate = 15/01/2
< Whiout finish the year > the Script is executed directly and i got the message Error :
document.getElementById('error-message').innerText = "The End Date must be greater than or equal to the Start Date";
Can You help me please ? i’m stake in this Scripts…
Find a solution for my question please
2
Answers
simply do a compare on dates delta => a negative values implies your test…
PS: it is useless and above all counterproductive not to use the automatic validation of HTML5 forms which only require the addition of a
required
attribute to ensure the conformity of the entries (empty fields, non-compliant values, etc.).Change both inputs to
type="date"
. Then the values will be in the formatYYYY-MM-DD
, which you can compare properly.Don’t use the
change
event. For some reason, this triggers in Chrome while you’re typing the year part of the date, so it will get an incomplete year. I’ve added a separate button to check the dates.To check whether the dates have been filled in, check whether they’re non-empty strings.
isNaN()
is only for numbers, not dates.