how to alert if the input date is greater than defined date in js

I am having an input date field in my form. In my date field i need to alert an error if the input date is greater than any date i define before here is what i code :

$(document).ready(function () {
    var date = new Date(2016,2,1); //the defined date is 1 March 2016
    var day = date.getDate();
    var month = date.getMonth();
    month = month + 1;

    if(day < 10){
        day = '0' + day;
    }

    if(month < 10){
        month='0'+month;
    }

    someday = day + '/' + month + '/' + date.getFullYear();

    $("#q1 input").blur(function(){   //#q1 is the ID for the input field.
        if($('#q1 input').val() > someday){
            alert('the input is bigger than the defined');
        }else{  
            alert('the defined is bigger than the input ');
        }
    });
});

Answers 1

  • To compare Dates is very straight forward. Most operators coerce the operands to number, and Dates return their time value so to see if today is before or after say 1 March 2016, create two Dates and compare them:

    var epoch = new Date(2016,2,1); // Create date for 2016-03-01T00:00:00
    var now   = new Date();         // Create a date for the current instant
    now.setHours(0,0,0,0);          // Set time to 00:00:00.000
    
    if (now < epoch) {
      alert('Before 1 March, 2016');
    } else {
      alert('On or after 1 March, 2016');
    }

    Or a bit more compact:

    alert((now < epoch? 'Before':'On or after') + ' 1 March, 2016');
    

Related Articles