结束日期大于开始日期mm / yyyy? jquery验证器

时间:2012-02-02 22:17:50

标签: jquery validation date split

我看到了这个例子:Validate that end date is greater than start date with jQuery

谈论结束日期的验证大于开始,我的输入的日期格式总是mm / yyyy,所以如果以下情况它对我不起作用: 开始日期> 122000 结束日期> 012002

我想我必须分开我的约会,只是检查yyyy,如果更大或没有,但不知道如何解决它...这是我的代码(我想总是说,如果我有我的输入中没有7个字符不通过表单提交:

HTML

<input type="text" id="starddate" />
<input type="text" id="enddate" />
<div id="msg"></div>
<input type="submit" id="submit" />

JS

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()) 
        || (parseFloat(value) > parseFloat($(params).val())); 
},'Must be greater than {0}.');

$("#enddate").rules('add', { greaterThan: "#startdate" });

1 个答案:

答案 0 :(得分:2)

如果您的日期值是字符串的格式为mm/yyyy,则您无法使用new Date(value)为其创建Date对象 - 这不是{Date格式1}}构造函数is documented as accepting(直到最近,除了toString的输出之外,没有任何记录可以接受任何内容,这也取决于实现的决定)。

但问题并不困难:鉴于dateA和dateB是该格式的字符串:

// Assumes the format mm/yyyy (not mmyyyy, which your example values seem to be in)
var compareA, compareB;
compareA = dateA.substring(3) + dateA.substring(0, 2);
compareB = dateB.substring(3) + dateB.substring(0, 2);
if (compareA > compareB) {
    // The date represented by `dateA` is later than the date
    // represented by `dateB`
}

或不太清楚

if (dateA.substring(3) + dateA.substring(0, 2) > dateB.substring(3) + dateB.substring(0, 2)) {
    // ...
}

例如,如果您在月份之前移动年份,则可以比较字符串,因为字符串"200012"<字符串"200201"