htmlangularmomentjsdatetime-formatangular-moment

how to restrict invalidate in input type datetime-local


<input type="datetime-local" step="1">

In that, how to avoid invalid date input. Suppose I am insert date like "11:11:1111" in "mm-dd-yyyy" format. how can solve this using Moment.js


Solution

  • Try using the isValid() method to make sure the DateTime is valid, or see my second example of checking if a date is older than a specified year. Example:

    // Variables
    var datetimeElement = document.getElementById("datetime");
    var statusElement = document.getElementById("status");
    
    // A simple function to check the validity of a date using the isValid() method
    function checkValidity() {
      if (moment(datetimeElement.value.toString()).isValid()) {
        // Datetime is in a valid format
        statusElement.innerHTML = 'Valid datetime';
      } else {
        // Invalid datetime format
        statusElement.innerHTML = 'Invalid datetime';
      }
    }
    
    // Check date validity every 1 seconds and update the text
    setInterval(function() {
        checkValidity();
      }, 1000);
    <input id="datetime" type="datetime-local" step="1">
    <p id="status"></p>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>

    In the example above, if you try and enter a date such as 11/11/11111, it will say that it is invalid. If you want to prevent dates that are before a specified year, you can use the following:

    // Variables
    var datetimeElement = document.getElementById("datetime");
    var statusElement = document.getElementById("status");
    
    // A simple function to check the validity of a date using the isValid() method
    function checkValidity() {
      if (moment(datetimeElement.value.toString()).isValid()) {
        // Datetime is in a valid format    
        // Check if datetime is older than the specified year (1900)
        if (moment(datetimeElement.value.toString()).format('YYYY') < 1900) {
          // Invalid date
          statusElement.innerHTML = 'Invalid datetime';
        } else {
          // Datetime is valid
          statusElement.innerHTML = 'Valid datetime';
        }
      } else {
        // Datetime is invalid
        statusElement.innerHTML = 'Invalid datetime';
      }
    }
    
    // Check date validity every 1 seconds and update the text
    setInterval(function() {
        checkValidity();
      }, 1000);
    <input id="datetime" type="datetime-local" step="1">
    <p id="status"></p>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>

    If you enter a year older than 1900, such as 01/01/1899, in the example code above, it will say it is invalid.

    I hope this has helped your problem.