如果提交日期声明

时间:2016-02-26 04:46:48

标签: javascript

需要以下声明的帮助:

是日期的表单提交,而不是必填字段。

我怎么能没有任何价值提交? 因为目前我无法在日期字段中提交没有值的表单。

谢谢

function ABC_StringIsDateFormatddMMyyyy(str) {
    if (str.length != 8) {
        return false;
    }
    var strYear = str.substring(4, 8);
    var strMonth = str.substring(2, 4);
    var strDay = str.substring(0, 2);
    if (isNaN(strYear)) {
        return false;
    }
    if (isNaN(strMonth)) {
        return false;
    }
    if (isNaN(strDay)) {
        return false;
    }

    var d = new Date();
    d.setFullYear(strYear, parseInt(strMonth) - 1, strDay);
    strYear = d.getFullYear();
    strMonth = d.getMonth() + 1;
    strMonth = "00" + strMonth;
    strMonth = strMonth.substring(strMonth.length - 2, strMonth.length);
    strDay = d.getDate();
    strDay = "00" + strDay;
    strDay = strDay.substring(strDay.length - 2, strDay.length);
    var tmp = strDay + strMonth + strYear;
    if (str != tmp) {
        return false;
    }
    return true;
}

1 个答案:

答案 0 :(得分:0)

如果字段为空,则返回true

function ABC_StringIsDateFormatddMMyyyy(str) {
    if (str.length == 0) {
        return true;
    }
    if (str.length != 8) {
        return false;
    }
    var strYear = str.substring(4, 8);
    var strMonth = str.substring(2, 4);
    var strDay = str.substring(0, 2);
    if (isNaN(strYear)) {
        return false;
    }
    if (isNaN(strMonth)) {
        return false;
    }
    if (isNaN(strDay)) {
        return false;
    }

    var d = new Date();
    d.setFullYear(strYear, parseInt(strMonth) - 1, strDay);
    strYear = d.getFullYear();
    strMonth = d.getMonth() + 1;
    strMonth = "00" + strMonth;
    strMonth = strMonth.substring(strMonth.length - 2, strMonth.length);
    strDay = d.getDate();
    strDay = "00" + strDay;
    strDay = strDay.substring(strDay.length - 2, strDay.length);
    var tmp = strDay + strMonth + strYear;
    if (str != tmp) {
        return false;
    }
    return true;
}