Javascript正则判断日期格式实例
例1
代码如下 | |
/** |
例2
代码如下 | |
/** |
例3
这里我们来一个比较完整的日期格式函数
代码如下 | |
//是否是日期格式 function CheckDate(strDate) { var reg = /^(d{4})-(d{2})-(d{2})$/; if (!reg.test(strDate)) { alert("日期格式不正确!/n正确格式为:2004-01-01"); return false; } var year = strDate.substring(0, 4); var month = strDate.substring(5, 7); var date = strDate.substring(8, 10); if (!checkYear(year)) { return false; } if (!checkMonth(month)) { return false; } if (!checkDate(year, month, date)) { return false; } return true; } function checkYear(year) { if (isNaN(parseInt(year))) { alert("年份输入有误,请重新输入!"); return false; } else if (parseInt(year) < 1950 || parseInt(year) > 2050) { alert("年份应该在1950-2050之间!"); return false; } else return true; } function checkMonth(month) { if (isNaN(parseInt(month, 10))) { alert("月份输入有误,请重新输入!"); return false; } else if (parseInt(month, 10) < 1 || parseInt(month, 10) > 12) { alert("月份应该在1-12之间"); return false; } else return true; } function checkDate(year, month, date) { var daysOfMonth = CalDays(parseInt(year), parseInt(month)); if (isNaN(parseInt(date))) { alert("日期输入有误,请重新输入!"); return false; } else if (parseInt(date) < 1 || parseInt(date) > daysOfMonth) { alert("日期应该在1-" + daysOfMonth + "之间!"); return false; } else return true; } function CalDays(year, month) { var date = new Date(year, month, 0); return date.getDate(); } function isLeapYear(year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) return true; else return false; } |