js实现日期验证

直接上代码:

function dateValidate(date, dateformat, separator) {

            if (date == null || date == "") return false;


            var date_part_index = datePartIndex(dateformat, separator);
            var date_array = date.split(separator);
            var yearstr = date_array[date_part_index.y];
            var monthstr = date_array[date_part_index.m];
            var daystr = date_array[date_part_index.d];

            if (isNaN(yearstr)) return false;
            if (isNaN(monthstr)) return false;
            if (isNaN(daystr)) return false;

            var year = parseInt(yearstr);
            var month = parseInt(monthstr)-1;
            var day = parseInt(daystr);
            var date = new Date(year, month, day);
            var y = date.getFullYear();
            var m = date.getMonth();
            var d = date.getDate();
            if (y != year || m != month || d != day) {
                return false;
            }
            return true;
        }

function datePartIndex(dateformat, separator) {
            var partIndex = {};
            var part_array = dateformat.split(separator);
            for (var i = 0; i < part_array.length; i++) {
                switch (part_array[i]) {
                    case "YYYY":
                        partIndex.y = i;
                        break;
                    case "MM":
                        partIndex.m = i;
                        break;
                    case "dd":
                        partIndex.d = i;
                        break;
                }
            }
            return partIndex;

}

dateValidate 是实现js日期验证的方法

datePartIndex 是实现js日期验证的辅助方法

 

下面日期证验的一些测试用例

alert(dateValidate("2005-10-21","YYYY-MM-dd","-") == true);
alert(dateValidate("2005-10-213","YYYY-MM-dd","-") == false);
alert(dateValidate("200a5-10-10","YYYY-MM-dd","-") == false);
alert(dateValidate("a2005-10-10","YYYY-MM-dd","-") == false);
alert(dateValidate("2005a-10-10","YYYY-MM-dd","-") == false);
alert(dateValidate("02005-1-1","YYYY-MM-dd","-") == true);
alert(dateValidate("2005-12-32","YYYY-MM-dd","-") == false);
alert(dateValidate("2005-13-3","YYYY-MM-dd","-") == false);
alert(dateValidate("2005-12-12","YYYY-MM-dd","-") == true);
alert(dateValidate("2005-2-30","YYYY-MM-dd","-") == false);
alert(dateValidate("2005-(-12)-3","YYYY-MM-dd","-") == false);
alert(dateValidate("2005-(12)-3","YYYY-MM-dd","-") == false);
alert(dateValidate("0-0-0","YYYY-MM-dd","-") == false);
alert(dateValidate("1-1-1","YYYY-MM-dd","-") == false);
alert(dateValidate("2005-2-30","YYYY-MM-dd","-") == false); 
alert(dateValidate("2012-2-30","YYYY-MM-dd","-") == false);
alert(dateValidate("2012-2-29","YYYY-MM-dd","-") == true);
alert(dateValidate("2012/2/29", "YYYY/MM/dd", "/") == true);
alert(dateValidate("2/29/2012", "MM/dd/YYYY", "/") == true);

以上测试用例的返回结果都应该是true,就正确。

posted on 2012-11-28 16:29  农民工老李  阅读(550)  评论(3编辑  收藏  举报

导航