[jquery] Validate that end date is greater than start date with jQuery

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

This question is related to jquery date jquery-validate

The answer is


this should work

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


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/


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

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


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


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


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

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

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

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

That should do it I think


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


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


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 {

}

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

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

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to jquery-validate

Phone Number Validation MVC Jquery Validate custom error message location Jquery validation plugin - TypeError: $(...).validate is not a function JQuery Validate input file type jquery to validate phone number Bootstrap with jQuery Validation Plugin jQuery Validation plugin: validate check box jQuery select box validation Confirm Password with jQuery Validate MVC 4 client side validation not working