skip to Main Content

I want to compare the already entered date with the newly entered date in one date input tag, and display a warning if the newly entered date is earlier than the already entered date.

However, the result of Invalid Date is coming out from the date entered previously.
So I can’t compare.
If anyone has experience with this, I’d be glad if you could help.

<div class="order-date">
                    <label for="order-date">発注日</label>
                    <input type="date" id="order_date" value="" class="input-style">
                </div>
var orderDate = document.getElementById("order_date");
let originalValue = orderDate.value;
orderDate.addEventListener("change", function(event) {
    let date = new Date(originalValue);
    let newValue = event.target.value;
    let newDate =  new Date(newValue);
    if(newDate < date) {
        alert("you can't select this date.");
    }
    console.log(date);
    console.log(newDate);
})

2

Answers


  1. The originalValue variable should have an initial value. Also, if the new date value is valid it should be saved to originalValue for the next compare.

    var oldDate = new Date(-1000, 1, 1);
    document.getElementById("order_date").addEventListener("change", order_date_Change);
    
    function order_date_Change(event) {
      var newDate = new Date(event.target.value);
      if (newDate < oldDate) {
        alert("you can't select this date.");
        event.target.valueAsDate = oldDate;
      }
      else {
        oldDate = newDate;
      }
    }
    <div class="order-date">
      <label for="order-date">Order Date</label>
      <input type="date" id="order_date" value="" class="input-style">
    </div>
    Login or Signup to reply.
  2. Likely invalid date is because the value of the date input isn’t set, so new Date is passed an empty string, which is parsed as an invalid date.

    In any case, the if value of the date input has been set, it will be parsed as UTC (because it’s format yyyy-mm-dd), but it’s compared to a local date which might give unexpected results within the local offset of midnight (which will appear to be ±1 day).

    Given the value of a date input is a date string (timestamp) in yyyy-mm-dd format, it can be compared to another date string of the same format using less than (<) and greater than (>) comparison operators. That avoids parsing of strings to dates and associated foibles.

    E.g.

    // Check if date is earlier than today
    function checkDate(evt) {
      let today = formatDateISO();
      let date = this.value;
      if (date !== '' & date < today) {
        console.log(`Enter a date on or after ${date}`);
        evt.preventDefault();
      } else {
        console.log(`I'm OK with ${date}`);
      }
    }
    
    // Helper - format local date as yyyy-mm-dd
    function formatDateISO(date = new Date()) {
      let z = n => ('0'+n).slice(-2);
      return `${date.getFullYear()}-` +
             `${z(date.getMonth() + 1)}-` +
             `${z(date.getDate())}`;  
    }
    
    // Onload, add listener and set date value to today
    window.onload = () => {
      let input = document.getElementById('order_date');
      input.defaultValue = formatDateISO();
      input.addEventListener('change', checkDate);
    }
    <div class="order-date">
      <label for="order-date">発注日</label>
      <input type="date" id="order_date">
    </div>

    This example just shows a message in the console, the response to the outcome can be whatever suits. Just don’t automatically clear the value that the user entered, let them change it themselves. If the value is cleared, they can’t see for themselves what they entered (which might be different from what they think they entered).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search