Do not allow insertion of a later date to another already inserted

4

I have an HTML form in which I give the user the ability to enter a start date and an end date, and of course I do not want the end date to be earlier than the start date.

Inputs for the dates are of the "datetime-local" type. My goal would be, after inserting Data Start , the fields with the days before the day entered in the Start Date would appear as "blocked" or so.

Code:

<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>
    
asked by anonymous 22.03.2017 / 18:41

1 answer

7

Just create an object of type Date and compare it normally if the first date is greater than the second.

One tip 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 returning 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 range. That is, if the first one was typed wrong, the user will need to put a valid end date before being able to edit the start date.

It is also possible to set the min attribute of the second input to equal (or greater) the date of the first as soon as it is clicked out of the first input. I will not make this code example because I do not know if it would fit the question the way it is and I do not even know if it interests 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><divclass="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>
    
22.03.2017 / 18:56