验证日期范围客户端

时间:2013-03-18 18:58:49

标签: javascript jquery

我有2个TextBox,期望格式为mm/dd/yyyy的日期 例如:

03/20/2013

在我甚至懒得进行ajax调用之前,我想尝试将这些转换为JS日期。我怎么能检查:

Both Dates are in the mm/dd/yyyy format and if they are, then From must be less than to.

由于

1 个答案:

答案 0 :(得分:1)

我建议使用这个时刻。 Moment是一个js库,特别适用于日期和评估日期。您的两个文本框以字符串开头,因此您需要每个文本框初始化2 moment()。然后验证它们都是时刻对象。如果是这样,那么确保一个接一个就是一个简单的事情。

以下是指向时刻的链接:http://momentjs.com/

这是我可以使用的代码:

var tb1 = $("#tb1").text(); // get string from "date box 1"
var tb2 = $("#tb2").text(); // get string from "date box 2"

//get timestamp val's so they can be used in moment initialization
var date1 = tb1.split("/"); 
var date2 = tb2.split("/");

    //create moments    
var mom1 = moment([date1[2], date1[1], date1[0]);
var mom2 = moment([date2[2], date2[1], date2[0]);

function validate(mom1, mom2){
    //validate both dates are actual dates
if (mom1.isValid() && mom2.isValid()){
            //compare timestamps to ensure 2nd timestamp is larger 
    if(mom1.unix() < mom2.unix()){
        return true;
    } else {
        return false;
    }
} else {
            //strings aren't dates, return error
    $.error("not valid dates");
}
}
相关问题