This question might be similar to this other question:
HTML Comparing 2 Dates with Javascript
But I don’t want to use a button
, simply make it instant.
I have 2 inputs of type date
and I want to compare between them.
JavaScript
x
28
28
1
<div>
2
<label style="font-family: 'Segoe UI';">Select a date.</label>
3
<br><br>
4
<span style="font-family: 'Segoe UI';">Since</span>
5
<input type="date" name="since" id="since" required="required" style="font-family: 'Segoe UI';"/>
6
7
<span style="font-family: 'Segoe UI';">Until</span>
8
<input type="date" name="until" id="until" required="required" style="font-family: 'Segoe UI';"/>
9
<br><br>
10
<button style="font-size: 14px; font-family: 'Segoe UI';" onclick="Validate()">COMPARE THIS</button>
11
</div>
12
13
<script type="text/javascript">
14
function Validate(){
15
var date1 = new Date(document.getElementById('since').value);
16
var date2 = new Date(document.getElementById('until').value);
17
18
if(date2 < date1) {
19
20
alert('The date cannot be less than the first date that you selected');
21
return false;
22
23
}else{
24
alert("It's OK");
25
return true;
26
}
27
}
28
</script>
Now the condition works perfectly, It compares the 2 dates and shows an error if the 2nd date is less than the first date. But this is using a button to trigger the comparison.
Is it possible to compare the input dates without a button to trigger the comparison? And using the HTMLSelectElement.setCustomValidity()
method?
Advertisement
Answer
I think you can use the onchange event to do this. I modified your snippet a little and put in a simple condition for when NOT to validate. You can adjust it to be more sophisticated.
JavaScript
1
30
30
1
<div>
2
<label style="font-family: 'Segoe UI';">Select a date.</label>
3
<br><br>
4
<span style="font-family: 'Segoe UI';">Since</span>
5
<input onchange="Validate()" type="date" name="since" id="since" required="required" style="font-family: 'Segoe UI';"/>
6
7
<span style="font-family: 'Segoe UI';">Until</span>
8
<input onchange="Validate()" type="date" name="until" id="until" required="required" style="font-family: 'Segoe UI';"/>
9
</div>
10
11
<script type="text/javascript">
12
function Validate(){
13
var input1 = document.getElementById('since').value;
14
var input2 = document.getElementById('until').value;
15
if(input1 != "" && input2 != ""){
16
var date1 = new Date(input1);
17
var date2 = new Date(input2);
18
19
if(date2 < date1) {
20
21
alert('The date cannot be less than the first date that you selected');
22
return false;
23
24
}else{
25
alert("It's OK");
26
return true;
27
}
28
}
29
}
30
</script>