<script>
function checkDate(str)
{
var date=new Date(str);
var y=date.getYear();
var m=date.getMonth()+1;
var d=date.getDate();
var myday=y + "/" + patch(m) + "/" + patch(d);
if (myday!=str)
{
alert(" 请输入一有效日期yyyy/mm/dd)!");
return false;
}
return true;
}function patch(n)
{
return (n-10<0) ? ("0"+n) : (""+n);
}
</script>
<input type=text id="test">
<input type=button value="是否日期" onclick="alert(checkDate(test.value))">
function checkDate(str)
{
var date=new Date(str);
var y=date.getYear();
var m=date.getMonth()+1;
var d=date.getDate();
var myday=y + "/" + patch(m) + "/" + patch(d);
if (myday!=str)
{
alert(" 请输入一有效日期yyyy/mm/dd)!");
return false;
}
return true;
}function patch(n)
{
return (n-10<0) ? ("0"+n) : (""+n);
}
</script>
<input type=text id="test">
<input type=button value="是否日期" onclick="alert(checkDate(test.value))">
}
http://www.csdn.net/Expert/topic/398/398039.shtm
不但保证"yyyy-mm-dd"格式,还可以根据月份判断日期是否正确,以及闰年的判断
我用
var date1=new Date(document.form1.polit_join_date.value);
得到的date1为'NaN',这是为什么啊??
比如2002年1月1日必须输入2002/01/01,若输2001/1/1会报错
如果不要这么严格的话,那只要去掉那个function patch(n)即可!
Months= new Array(31,28,31,30,31,30,31,31,30,31,30,31);
Leap = false;if((Y % 4 == 0) && ((Y % 100 != 0) || (Y %400 == 0)))
Leap = true;
if((D < 1) || (D > 31) || (M < 1) || (M > 12) || (Y < 0))
return(false);
if((D > Months[M-1]) && !((M == 2) && (D > 28)))
return(false);
if(!(Leap) && (M == 2) && (D > 28))
return(false);
if((Leap) && (M == 2) && (D > 29))
return(false);
};
function formatDate(dateForm){
cDate = dateForm.value;
dSize = cDate.length;
sCount= 0;
if (dateForm.value == ""){
alert("请输入日期!");
return false ;
}
if(cDate=='') return;
for(var i=0; i < dSize; i++)
(cDate.substr(i,1) == "-") ? sCount++ : sCount;
if (sCount != 2){
alert("输入的日期格式必须是\n ''年-月-日''");
dateForm.focus();
return(false);
}
//检测输入的年份是2位数还是4位数;
ySize =cDate.substring(0,cDate.indexOf("-")).length;
if(ySize!=4){
alert('您输入的日期错误 !');
dateForm.focus();
return false;
}
//将输入的日期字符串分隔成3部分 (Month, Day & Year)
idxBarI = cDate.indexOf("-");
idxBarII= cDate.lastIndexOf("-");
strY = cDate.substring(0,idxBarI);
strM = cDate.substring(idxBarI+1,idxBarII);
strD = cDate.substring(idxBarII+1,dSize);strM = (strM.length < 2 ? '0'+strM : strM);
strD = (strD.length < 2 ? '0'+strD : strD);
if(strY.length == 2)
strY = (strY > 50 ? '19'+strY : '20'+strY);
dateForm.value = strY+'-'+strM+'-'+strD;ok = valDate(strM, strD, strY);
if(ok==false){
alert("您输入的日期错误 !");
dateForm.focus();
return false;
}
return true;
}