Skip to content Skip to sidebar Skip to footer

Javascript - Date Range Validation

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 not in

Solution 1:

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:

functionvalidation(form) {
    var v2 = document.getElementById('v2'),
      date = newDate(v2.value),
      d1   = date.getTime(),
      d2   = newDate('12/12/2012').getTime(),
      d3   = newDate('1/1/2013').getTime();

   if (d1 > d2 || d1 < d3) {
       returntrue;
   }else{
       alert("date is not in valid range")
   }
}

Solution 2:

You can make a function like this:

functioncheckMyDateWithinRange(myDdate){
    var startDate = newDate(2012, 11, 1);
    var endDate = newDate(2012, 0, 1);     
    if (startDate < myDate && myDate < endDate) {
       returntrue; 
    }
   returnfalse;
}

and test any date like calling this function:

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

Here is Working Demo

Post a Comment for "Javascript - Date Range Validation"