日期,日期时间类型数据格式校验
<script>
function testDatatime(){
alert(!"2010-01-29 12:44:12.1022".isDateTime());
alert("2010-01-29 12:44:12.122".isDateTime());
alert(!"2010-01-29 24:44:12".isDateTime());
alert("2010-3-31 12:44:12".isDateTime());
alert(!"1900-2-29 12:44:12".isDateTime());
alert(!"1900-4-31 12:44:12".isDateTime());
alert("1904-2-29 12:44:12".isDateTime());
}
function testData(){
alert("2010-01-29".isDate());
alert(!"2010-01-32".isDate());
alert("2010-3-31".isDate());
alert(!"1900-2-29".isDate());
alert(!"1900-4-31".isDate());
alert("1904-2-29".isDate());
}
String.prototype.isDateTime = function() {
var r = this.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})(\.[0-9]{1,3})?$/);
if(r==null)return false;
var d = new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]);
return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]);
} ;
String.prototype.isDate = function(){
var r = this.match(/^(\d[0-9]{1,4})(-|\/)(\d[0-9]{1,2})\2(\d[0-9]{1,2})/);
if(r==null) return false;
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]);
};
String.prototype.isTime = function(){
var r = this.match(/^(\d{1,2}):(\d{1,2}):(\d{1,2})(\.[0-9]{1,3})?$/);
if(r==null) return false;
return true;
}
function checkDate(){
var df=document.getElementById('dateField');
var info=df.value;
if(info.length!=10){
alert('The date format error! it must be yyyy-mm-dd!\n Example: 2010-02-05, 2010-12-05. ');
return false;
}
var rs=info.isDate();
if(!rs) {
alert('The date format error ! '+info);
return false;
}else alert('right date format! '+info);
}
function checkDateTime(){
var df=document.getElementById('datetimeField');
var info=df.value;
var index=info.indexOf('.');
if(index<0&&info.length!=19||index>0&&index<19){
alert('The date format error! it must be yyyy-MM-dd HH:mm:ss.S!\n Example: 2010-02-05 06:05:09, 2010-12-05 12:35:08, 2010-12-05 12:35:08.123 ');
return false;
}
var rs=info.isDateTime();
if(!rs) {
alert('The datetime format error ! '+info);
return false;
}else alert('right datetime format! '+info);
}
function checkTime(){
var df=document.getElementById('timeField');
var info=df.value;
var index=info.indexOf('.');
if(index<0&&info.length!=8||index>0&&index<8){
alert('The date format error! it must be HH:mm:ss.S!\n Example:06:05:09, 12:35:08, 12:35:08.123 ');
return false;
}
var rs=info.isTime();
if(!rs) {
alert('The time format error ! '+info);
return false;
}else alert('right time format! '+info);
}
</script>
<p>Date format: <input type="text" size="15" value="2010-02-19" id="dateField" ><button type=button onclick="checkDate()">Check</button>
<p>DateTime format: <input type="text" size="30" id="datetimeField" ><button type=button onclick="checkDateTime()">Check</button>
<p>Time format: <input type="text" size="30" id="timeField" ><button type=button onclick="checkTime()">Check</button>