date range validation is valid if 'to date' not in same month as 'from date'

1k views Asked by At

I have search date range 'from date' & 'to date' my validation function make data valid if range of date is not in same month ? for example if from date"2015-06-02" to date "2015-06-01" the range is invalid range? but if I make the to date "2015-05-31" it will be valid range if range in same monthif range not in same month

var validateDateRange = function () {
    var fromDate = moment($scope.model.fromDateSearch, 'MM-DD-YYYY');
    var toDate = moment($scope.model.toDateSearch, 'MM-DD-YYYY');
    var a = (fromDate > toDate) ;
    return a;

};

2

There are 2 answers

0
Asheesh Kumar On BEST ANSWER

There is some problem with date format you are passing. So it would also work if you just remove the format and just pass in the value.

Run and check the code snippet below its working fine

var validateDateRange = function (fromDate, toDate) {
    var fromDate = moment(fromDate);
    var toDate = moment(toDate);
    var a = (fromDate > toDate) ;
    return a;

};

var fromDate= new Date("2015-06-02");
var toDate = new Date("2015-06-01");
alert(validateDateRange(fromDate, toDate));

var fromDate= new Date("2015-06-02");
var toDate = new Date("2015-05-31");
alert(validateDateRange(fromDate, toDate));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.js"></script>

0
couscousman On

You should use the number of milliseconds since the Unix Epoch, it is safer.

var validateDateRange = function () {
    var fromDate = moment($scope.model.fromDateSearch, 'MM-DD-YYYY').valueOf();
    var toDate = moment($scope.model.toDateSearch, 'MM-DD-YYYY').valueOf();
    var a = (fromDate < toDate) ;
    return a;
};

Note the 'lower than' sign.