Validate that end date is greater than start date with jQuery

JqueryDateJquery Validate

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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" }
    }
});

Solution 2 - Jquery

var startDate = new Date($('#startDate').val());
var endDate = new Date($('#endDate').val());

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

That should do it I think

Solution 3 - Jquery

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");
}

Solution 4 - Jquery

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 :-)

Solution 5 - Jquery

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 https://stackoverflow.com/questions/18082/validate-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}.');

Solution 6 - Jquery

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.');

Solution 7 - Jquery

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/

Solution 8 - Jquery

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

Solution 9 - Jquery

$(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

Solution 10 - Jquery

jQuery('#from_date').on('change', function(){
    var date = $(this).val();
    jQuery('#to_date').datetimepicker({minDate: date});  
});

Solution 11 - Jquery

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;
}

Solution 12 - Jquery

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 :)

Solution 13 - Jquery

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 {

}

Solution 14 - Jquery

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");

Solution 15 - Jquery

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' });

Solution 16 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioninputView Question on Stackoverflow
Solution 1 - JqueryMike E.View Answer on Stackoverflow
Solution 2 - JqueryShane O'GradyView Answer on Stackoverflow
Solution 3 - JqueryKamran AhmedView Answer on Stackoverflow
Solution 4 - JqueryRussell GiddingsView Answer on Stackoverflow
Solution 5 - JqueryJonView Answer on Stackoverflow
Solution 6 - JqueryCharityView Answer on Stackoverflow
Solution 7 - JqueryFranzView Answer on Stackoverflow
Solution 8 - JqueryKBCView Answer on Stackoverflow
Solution 9 - JquerysaggyView Answer on Stackoverflow
Solution 10 - JqueryAtchyut NagabhairavaView Answer on Stackoverflow
Solution 11 - JqueryStefanNchView Answer on Stackoverflow
Solution 12 - JquerySantosh KoriView Answer on Stackoverflow
Solution 13 - JquerySuraj KhotView Answer on Stackoverflow
Solution 14 - JqueryBagaskaraView Answer on Stackoverflow
Solution 15 - JqueryfahdshaykhView Answer on Stackoverflow
Solution 16 - JqueryNadia AlramliView Answer on Stackoverflow