vapcguy vapcguy - 5 months ago 53
jQuery Question

Moment.js - Date comparison: Catching min range

My form has a Kendo DatePicker and a button that runs a JavaScript function prior to doing a form.submit(). I need to be able to compare my date that is entered against a lower limit, and prevent the code from going on (submitting the form) if it is earlier than my set date. I want to return false if the limit hasn't been breached, true if it has. I'll use this example to show what I'm trying to do in the validation code:

var lowerBound = new Date('1776', '6','4'); // July 4, 1776
var dateField = $('#myDateField').val(); // <-- comes from Kendo DatePicker
var dateToConsider = new Date(dateField); // if this is 1/1/0001, this changes to 1/1/1901... not good, so I do this, instead....

var arrDate = dateField.split('/'); // I also check for '-', ' ', and '.'
dateToConsider = arrDate[2] + '-' + arrDate[0] + '-' arrDate[1]; // could add 'T00:00:00Z'; but don't think it matters

var momentDTC = moment(dateToConsider);
var lowerLimitBreached = moment(lowerBound).isAfter(momentDTC); // <-- this is always false

if (!lowerLimitBreached)
$('form').submit();


I've been inputting 1/1/0001 into the control, and it keeps giving
lowerLimitBreached
as false, when it should be true, since 1-1-0001 is clearly earlier than 7-4-1776... I tried using
.isBefore()
, but met with the same issue, and the documentation actually says
NOTE: moment().isBefore() has undefined behavior and should not be used!
, so I dare not use that.

Moment documentation: http://momentjs.com/docs/#/query/

Answer

Since you're using moment.js, don't use the JavaScript Date object at all. Stick to moment objects only.

//evaluates correctly
moment('0001-01-01');

//evaluates to Feb 2, 0001 - makes no sense...
new Date(Date.parse('0001-02-03'))
                            //^ but that's a 3, not a 2

//true - Jan 1, 0001 is before June 4, 1776
moment('0001-01-01').diff(moment('1776-06-04')) < 0

So, looking at your code, try this out:

var lowerBound = moment('1776-06-04');
var dateField = $('#myDateField').val();

// String replace and put in proper format for moment
dateField = dateField.replace(/(\/)/g,'-');
var year = dateField.split('-')[2];
var month = dateField.split('-')[0];
var day = dateField.split('-')[1];

if (month < 10) { month = "0" + month; }
if (day < 10) { day = "0" + day; }
dateField = year + '-' + month + '-' + day;

// Enter into moment and compare
var dateToConsider = moment(dateField);
var lowerLimitBreached = dateToConsider.diff(lowerBound) < 0;

if (lowerLimitBreached)
    $('form').submit();
Comments