118

How do I check/validate in jQuery whether end date [textbox] is greater than start date [textbox]?

Jason
  • 15,017
  • 23
  • 85
  • 116
input
  • 7,503
  • 25
  • 93
  • 150
  • There is a solution here: http://stackoverflow.com/questions/17169772/how-to-compare-two-datepicker-date-jquery – Adrian P. Aug 03 '15 at 15:21

16 Answers16

191

Just expanding off fusions answer. this extension method works using the jQuery validate plugin. It will validate dates and numbers

jQuery.validator.addMethod("greaterThan", 
function(value, element, params) {

    if (!/Invalid|NaN/.test(new Date(value))) {
        return new Date(value) > new Date($(params).val());
    }

    return isNaN(value) && isNaN($(params).val()) 
        || (Number(value) > Number($(params).val())); 
},'Must be greater than {0}.');

To use it:

$("#EndDate").rules('add', { greaterThan: "#StartDate" });

or

$("form").validate({
    rules: {
        EndDate: { greaterThan: "#StartDate" }
    }
});
Jon
  • 428,835
  • 81
  • 738
  • 806
Mike E.
  • 2,163
  • 1
  • 15
  • 13
  • How do you use this with two text boxes? – Cros Sep 24 '10 at 15:23
  • 1
    I had to modify it slightly to allow for blank end dates in my app, but this did the bulk. `code` if (value == 0) { return true; } else if (!/Invalid|NaN/... `code` – Frank Luke Jun 23 '11 at 14:48
  • 3
    **BUG warning:** I do realize the question is about dates, but this code will not work for numbers as advertised. I have added [an answer](http://stackoverflow.com/a/10298956/50079) explaining the why and the how which also includes the fix. – Jon Apr 24 '12 at 13:34
  • 1
    @Cros jQuery.validator.addMethod("zip_code_checking", function(value, element) { return jQuery('#zip_endvalue').val() > jQuery('#zip_startvalue').val() }, "* Zip code end value should be greater than Zip code start value"); – Balasuresh Asaithambi Aug 18 '16 at 11:32
  • This yields an error in Google chrome. If you pass a value less than 12 or greater than 31, it ends up being parsed as a date, and hence it's validated as a date as well. I had to separate this into two methods (in hurry), but I'd love to find a more suitable solution! – sbsatter Jun 11 '17 at 04:54
  • how would this work if you had three separate fields for each date DD MM YYYY – user3486427 Oct 12 '18 at 08:05
  • Issue coming when we updating End date to correct our form. For this I updated this code. $('#EndDate').on('change',function(){ $("#EndDate").rules() }) – Nids Barthwal Aug 01 '22 at 10:08
89
var startDate = new Date($('#startDate').val());
var endDate = new Date($('#endDate').val());

if (startDate < endDate){
// Do something
}

That should do it I think

Shane O'Grady
  • 2,465
  • 18
  • 20
22

Little late to the party but here is my part

Date.parse(fromDate) > Date.parse(toDate)

Here is the detail:

var from = $("#from").val();
var to = $("#to").val();

if(Date.parse(from) > Date.parse(to)){
   alert("Invalid Date Range");
}
else{
   alert("Valid date Range");
}
Kamran Ahmed
  • 11,809
  • 23
  • 69
  • 101
15

Reference jquery.validate.js and jquery-1.2.6.js. Add a startDate class to your start date textbox. Add an endDate class to your end date textbox.

Add this script block to your page:-

<script type="text/javascript">
    $(document).ready(function() {
        $.validator.addMethod("endDate", function(value, element) {
            var startDate = $('.startDate').val();
            return Date.parse(startDate) <= Date.parse(value) || value == "";
        }, "* End date must be after start date");
        $('#formId').validate();
    });
</script>

Hope this helps :-)

Community
  • 1
  • 1
Russell Giddings
  • 8,731
  • 5
  • 34
  • 35
13

I was just tinkering with danteuno's answer and found that while good-intentioned, sadly it's broken on several browsers that are not IE. This is because IE will be quite strict about what it accepts as the argument to the Date constructor, but others will not. For example, Chrome 18 gives

> new Date("66")
  Sat Jan 01 1966 00:00:00 GMT+0200 (GTB Standard Time)

This causes the code to take the "compare dates" path and it all goes downhill from there (e.g. new Date("11") is greater than new Date("66") and this is obviously the opposite of the desired effect).

Therefore after consideration I modified the code to give priority to the "numbers" path over the "dates" path and validate that the input is indeed numeric with the excellent method provided in Validate decimal numbers in JavaScript - IsNumeric().

In the end, the code becomes:

$.validator.addMethod(
    "greaterThan",
    function(value, element, params) {
        var target = $(params).val();
        var isValueNumeric = !isNaN(parseFloat(value)) && isFinite(value);
        var isTargetNumeric = !isNaN(parseFloat(target)) && isFinite(target);
        if (isValueNumeric && isTargetNumeric) {
            return Number(value) > Number(target);
        }

        if (!/Invalid|NaN/.test(new Date(value))) {
            return new Date(value) > new Date(target);
        }

        return false;
    },
    'Must be greater than {0}.');
Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806
6

So I needed this rule to be optional and none of the above suggestions are optional. If I call the method it is showing as required even if I set it to needing a value.

This is my call:

  $("#my_form").validate({
    rules: {
      "end_date": {
        required: function(element) {return ($("#end_date").val()!="");},
        greaterStart: "#start_date"
      }
    }
  });//validate()

My addMethod is not as robust as Mike E.'s top rated answer, but I'm using the JqueryUI datepicker to force a date selection. If someone can tell me how to make sure the dates are numbers and have the method be optional that would be great, but for now this method works for me:

jQuery.validator.addMethod("greaterStart", function (value, element, params) {
    return this.optional(element) || new Date(value) >= new Date($(params).val());
},'Must be greater than start date.');
Sumoanand
  • 8,835
  • 2
  • 47
  • 46
Charity
  • 107
  • 1
  • 5
5

The date values from the text fields can be fetched by jquery's .val() Method like

var datestr1 = $('#datefield1-id').val();
var datestr2 = $('#datefield2-id').val();

I'd strongly recommend to parse the date strings before comparing them. Javascript's Date object has a parse()-Method, but it only supports US date formats (YYYY/MM/DD). It returns the milliseconds since the beginning of the unix epoch, so you can simply compare your values with > or <.

If you want different formats (e.g. ISO 8661), you need to resort to regular expressions or the free date.js library.

If you want to be super user-fiendly, you can use jquery ui datepickers instead of textfields. There is a datepicker variant that allows to enter date ranges:

http://www.filamentgroup.com/lab/date_range_picker_using_jquery_ui_16_and_jquery_ui_css_framework/

Franz
  • 1,324
  • 8
  • 2
4

In javascript/jquery most of the developer uses From & To date comparison which is string, without converting into date format. The simplest way to compare from date is greater then to date is.

Date.parse(fromDate) > Date.parse(toDate)

Always parse from and to date before comparison to get accurate results

Jithin Raj P R
  • 6,667
  • 8
  • 38
  • 69
KBC
  • 43
  • 3
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/low-quality-posts/18026392) – Mamun Nov 22 '17 at 08:28
  • It is solution to question. I have tried and answered. – KBC Nov 27 '17 at 14:11
  • Date.parse() always parses to MM/DD/YYYY format try best solution. – fahdshaykh May 24 '21 at 10:08
3
$(document).ready(function(){
   $("#txtFromDate").datepicker({
        minDate: 0,
        maxDate: "+60D",
        numberOfMonths: 2,
        onSelect: function(selected) {
          $("#txtToDate").datepicker("option","minDate", selected)
        }
    });

    $("#txtToDate").datepicker({
        minDate: 0,
        maxDate:"+60D",
        numberOfMonths: 2,
        onSelect: function(selected) {
           $("#txtFromDate").datepicker("option","maxDate", selected)
        }
    });
});

Or Visit to this link

croxy
  • 4,082
  • 9
  • 28
  • 46
saggy
  • 47
  • 3
3
jQuery('#from_date').on('change', function(){
    var date = $(this).val();
    jQuery('#to_date').datetimepicker({minDate: date});  
});
CubeJockey
  • 2,209
  • 8
  • 24
  • 31
Atchyut Nagabhairava
  • 1,295
  • 3
  • 16
  • 23
2

I like what Franz said, because is what I'm using :P

var date_ini = new Date($('#id_date_ini').val()).getTime();
var date_end = new Date($('#id_date_end').val()).getTime();
if (isNaN(date_ini)) {
// error date_ini;
}
if (isNaN(date_end)) {
// error date_end;
}
if (date_ini > date_end) {
// do something;
}
StefanNch
  • 2,569
  • 24
  • 31
1
function endDate(){
    $.validator.addMethod("endDate", function(value, element) {
      var params = '.startDate';
        if($(element).parent().parent().find(params).val()!=''){
           if (!/Invalid|NaN/.test(new Date(value))) {
               return new Date(value) > new Date($(element).parent().parent().find(params).val());
            }
       return isNaN(value) && isNaN($(element).parent().parent().find(params).val()) || (parseFloat(value) > parseFloat($(element).parent().parent().find(params).val())) || value == "";              
      }else{
        return true;
      }
      },jQuery.format('must be greater than start date'));

}

function startDate(){
            $.validator.addMethod("startDate", function(value, element) {
            var params = '.endDate';
            if($(element).parent().parent().parent().find(params).val()!=''){
                 if (!/Invalid|NaN/.test(new Date(value))) {
                  return new Date(value) < new Date($(element).parent().parent().parent().find(params).val());
            }
           return isNaN(value) && isNaN($(element).parent().parent().find(params).val()) || (parseFloat(value) < parseFloat($(element).parent().parent().find(params).val())) || value == "";
                 }
                        else{
                     return true;
}

    }, jQuery.format('must be less than end date'));
}

Hope this will help :)

Santosh Kori
  • 461
  • 4
  • 12
0

First you split the values of two input box by using split function. then concat the same in reverse order. after concat nation parse it to integer. then compare two values in in if statement. eg.1>20-11-2018 2>21-11-2018

after split and concat new values for comparison 20181120 and 20181121 the after that compare the same.

var date1 = $('#datevalue1').val();
var date2 = $('#datevalue2').val();
var d1 = date1.split("-");
var d2 = date2.split("-");

d1 = d1[2].concat(d1[1], d1[0]);
d2 = d2[2].concat(d2[1], d2[0]);

if (parseInt(d1) > parseInt(d2)) {

    $('#fromdatepicker').val('');
} else {

}
0

this should work

$.validator.addMethod("endDate", function(value, element) {
            var startDate = $('#date_open').val();
            return Date.parse(startDate) <= Date.parse(value) || value == "";
        }, "* End date must be after start date");
Bagaskara
  • 812
  • 8
  • 15
0

you can do on two different dates for alert like this.

$('#end_date').on('change', function(){
             var startDate = $('#start_date').val();
             var endDate = $('#end_date').val();
             if (endDate < startDate){
                 alert('End date should be greater than Start date.');
                $('#end_date').val('');
             }
         });

either you can perform on calendar it will automatically disable previous dates.

$("#start_date").datepicker({
            dateFormat: 'dd/mm/yy',
            onSelect: function(date) {
                $("#end_date").datepicker('option', 'minDate', date);
            }
        });
$("#end_date").datepicker({ dateFormat: 'dd/mm/yy' });
fahdshaykh
  • 472
  • 3
  • 10
-2

If the format is guaranteed to be correct YYYY/MM/DD and exactly the same between the two fields then you can use:

if (startdate > enddate) {
   alert('error'
}

As a string comparison

Nadia Alramli
  • 111,714
  • 37
  • 173
  • 152