Javascript - date range validation

前端 未结 2 515
清酒与你
清酒与你 2021-01-23 08:36

i\'ve a form user can enter any date , but i want to set a date range validation . for example: from 1-12-2012 to 1-1-2013 and the system can\'t accept any date from user that n

相关标签:
2条回答
  • 2021-01-23 08:53

    You can make a function like this:

    function checkMyDateWithinRange(myDdate){
        var startDate = new Date(2012, 11, 1);
        var endDate = new Date(2012, 0, 1);     
        if (startDate < myDate && myDate < endDate) {
           return true; 
        }
       return false;
    }
    

    and test any date like calling this function:

    var inputDate= document.getElementById('tbDate'),
    date = new Date(inputDate.value);
    if(!checkMyDateWithinRange(date)){
        alert('Date is not in range!!!');
    }
    

    Here is Working Demo

    0 讨论(0)
  • 2021-01-23 08:57

    To compare dates, you should be using the unix timestamp, and right now the first date you're getting from the value is a string, and you can't compare that against date objects?

    Make sure you have timestamps in unix time, and then compare those:

    function validation(form) {
        var v2 = document.getElementById('v2'),
          date = new Date(v2.value),
          d1   = date.getTime(),
          d2   = new Date('12/12/2012').getTime(),
          d3   = new Date('1/1/2013').getTime();
    
       if (d1 > d2 || d1 < d3) {
           return true;
       }else{
           alert("date is not in valid range")
       }
    }
    
    0 讨论(0)
提交回复
热议问题