0

我的表单有一个 Kendo DatePicker 和一个在执行 form.submit() 之前运行 JavaScript 函数的按钮。我需要能够将输入的日期与下限进行比较,如果代码早于我设定的日期,则阻止代码继续(提交表单)。如果没有违反限制,我想返回 false,如果有,则返回 true。我将使用这个示例来展示我在验证代码中要执行的操作:

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

我一直在将 1/1/0001 输入到控件中lowerLimitBreached,当它应该为真时,它一直给出错误,因为 1-1-0001 显然早于 7-4-1776 ...我尝试使用.isBefore(),但是遇到了同样的问题,文档实际上说NOTE: moment().isBefore() has undefined behavior and should not be used!,所以我不敢使用。

时刻文档: http: //momentjs.com/docs/#/query/

4

2 回答 2

0

由于您使用的是 moment.js,所以根本不要使用 JavaScript Date 对象。只坚持时刻对象。

//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

所以,看看你的代码,试试这个:

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();
于 2015-03-25T01:26:24.617 回答
-1

你为什么不这样做?

var lowerBound = moment('1776-6-4');
var dateField = moment($('#myDateField').val());
var lowerLimitBreached = moment(lowerBound).isAfter(dateField);

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

您已经在使用时刻,只需将剑道选择器的日期转换为时刻对象并使用isAfteror isBefore

如果这不起作用,请提供选择器可能返回的日期,该日期不适合您

于 2015-03-25T01:38:22.277 回答