Skip to content
Advertisement

Compare date values “instantly” on user input

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.

<div>
  <label style="font-family: 'Segoe UI';">Select a date.</label>
  <br><br>
  <span style="font-family: 'Segoe UI';">Since</span>&nbsp;
  <input type="date" name="since"  id="since" required="required" style="font-family: 'Segoe UI';"/>&nbsp;&nbsp;

  <span style="font-family: 'Segoe UI';">Until</span>&nbsp;
  <input type="date" name="until" id="until" required="required" style="font-family: 'Segoe UI';"/>
  <br><br>
  <button style="font-size: 14px; font-family: 'Segoe UI';" onclick="Validate()">COMPARE THIS</button>
</div>

<script type="text/javascript">
  function Validate(){
    var date1 = new Date(document.getElementById('since').value);
    var date2 = new Date(document.getElementById('until').value);
  
    if(date2 < date1) {

        alert('The date cannot be less than the first date that you selected');
        return false;

    }else{
        alert("It's OK");
        return true;
    }
  }
</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.

<div>
  <label style="font-family: 'Segoe UI';">Select a date.</label>
  <br><br>
  <span style="font-family: 'Segoe UI';">Since</span>&nbsp;
  <input onchange="Validate()" type="date" name="since"  id="since" required="required" style="font-family: 'Segoe UI';"/>&nbsp;&nbsp;

  <span style="font-family: 'Segoe UI';">Until</span>&nbsp;
  <input onchange="Validate()" type="date" name="until" id="until" required="required" style="font-family: 'Segoe UI';"/>
</div>

<script type="text/javascript">
  function Validate(){
    var input1 = document.getElementById('since').value;
    var input2 = document.getElementById('until').value;
  if(input1 != "" && input2 != ""){
      var date1 = new Date(input1);
      var date2 = new Date(input2);

      if(date2 < date1) {

          alert('The date cannot be less than the first date that you selected');
          return false;

      }else{
          alert("It's OK");
          return true;
      }
    }
  }
</script>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement