<!doctype html><html><head><meta charset="utf-8"><title>日期输入</title><script>window.onload = function(){var aLaydate = document.getElementsByClassName("date");for(var i = 0;i < aLaydate.length;i ++){aLaydate[i].onchange = function(){var dateValue = this.value;dateValue = dateValue.replace(//。/g,"-");dateValue = dateValue.replace(//./g,"-");if(dateValue.length == 8){var temp = dateValue.substring(0,4) + "-" + dateValue.substring(4,6) + "-" + dateValue.substring(6,8);dateValue = temp;console.log(dateValue);}if(CheckDT(dateValue)){this.value = dateValue;}else{alert("日期输入错误");}}}}function CheckDT(str) { var r = str.match(/^(/d{1,4})(-|//)(/d{1,2})/2(/d{1,2})$/); if(r==null) { return false; } else { var d= new Date(r[1], r[3]-1, r[4]); return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]); } }</script></head><body><input placeholder="请输入日期" class="date"></body></html>
把输入的YYYY.MM.DD、YYYY。MM。DD、YYYYMMDD转为YYYY-MM-DD
CheckDT这个function是找的园子里的。
新闻热点
疑难解答