Just create an object of the type Date
and normally compare whether the first date is greater than the second.
A hint is to check if the end date is valid when trying to exit the second input and, if it is not, show some message and return the focus to the second input
.
Note that the idea of turning the focus to input if the input is invalid seems interesting at first, but will block the user from trying to modify the first date without first entering a valid interval. That is, if the first one has been typed wrong, the user will need to put a valid end date to later be able to edit the start date.
It is also possible to set the attribute min
of the second input equal (or greater) to the date of the first one once it is clicked out of the first input. I’m not going to do this example in code because I don’t know if it would fit the question the way it is and I don’t even know if it matters to you.
$('#date-form2').on('focusout', function(){
var dateObj1 = new Date($('#date-form1').val());
var dateObj2 = new Date($('#date-form2').val());
if(dateObj1.getTime() > dateObj2.getTime()){
$(this).css({color: 'red'});
// mostre alguma mensagem
$(this).focus(); // Volta o foco para o segundo input
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="date-form1">Data/Hora Inicio</label>
<input class="form-control" type="datetime-local" name="date-beginning" id="date-form1">
</div>
<!-- Data Fim -->
<div class="form-group">
<label for="date-form2">Data/Hora Fim</label>
<input class="form-control" type="datetime-local" name="date-end" id="date-form2">
</div>
Do you use a JS library to manipulate dates? Like momentjs and the like.
– Jéf Bueno
No, I am not using a @jbueno library
– Vítor Sá
Oi Vitor, inputs of the kind
datetime-local
have an attribute calledmin
. You can do Binding of this attribute indate-end
with the value ofdate-beginning
. Are you using a Javascript library? Angular or something like that?– Anthony Accioly