可以用vbscript 定義 , 在javascript 裡面引用!
<script language="vbscript">
function isDate(strDate)
on error resume next '''這一句很重要
strDate = CDate(CStr(strDate)) '''如果不是出錯
if err.Number = 0 then '''捕捉 錯誤對象err 是否發生
return(true) ''' 沒有發生 , 成功
else
return(false) ''' 出錯 , 說明strDate不是日期型字符
end if
end function
</script>
the simplest way is like this:
<script language="javascript">
var str = "12/12/2001";
var dt = new Date(str);
if (!isNaN(dt))
{
//是date
}
else
{
//not a date
}
</script>
But this method has a problem: if your date string is "12/32/2001", it is still a valid date. Internally, it will be "1/1/2002"
function validateUSDate( strValue ) {
// var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
var objRegExp = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
//check to see if in correct format
if(strValue=="") return true;
else if(!objRegExp.test(strValue))
return false; //doesn't match pattern, bad date
else{
var arrayDate = strValue.split(RegExp.$1); //split date into month, day, year
var intDay = parseInt(arrayDate[2],10);
var intYear = parseInt(arrayDate[0],10);
var intMonth = parseInt(arrayDate[1],10);
//check for valid month
if(intMonth > 12 || intMonth < 1) {
return false;
}
//create a lookup for months not equal to Feb.
var arrayLookup = { '01' : 31,'03' : 31, '04' : 30,'05' : 31,'06' : 30,'07' : 31,'08' : 31,'09' : 30,'10' : 31,'11' : 30,'12' : 31,'1' : 31,'3' : 31, '4' : 30,'5' : 31,'6' : 30,'7' : 31,'8' : 31,'9' : 30}
//check if month value and day value agree
if(arrayLookup[arrayDate[1]] != null) {
if(intDay <= arrayLookup[arrayDate[1]] && intDay != 0)
return true; //found in lookup table, good date
}
//check for February
var booLeapYear = (intYear % 4 == 0 && (intYear % 100 != 0 || intYear % 400 == 0));
if( ((booLeapYear && intDay <= 29) || (!booLeapYear && intDay <=28)) && intDay !=0)
return true; //Feb. had valid number of days
}
return false; //any other values, bad date
}
这段程序关键在于正则表达式要正确
注释掉的是原先老美的世界格式:mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy
未注释的中国格式:yyyy/mm/dd or yyyy-mm-dd or yyyy.mm.dd
后面的是年月日的正确性检查
这样使用 var check=validateUSDate('2001-11-30')
check 是 true 为正确 false 为错误