////////////////////////////////////////////////////////
//检查输入的时间是否符合指定的格式//
///////////////////////////////////////////////////////
function checkT(strTC)
{
flg=0;
temp="";
for (var i=0;i<strTC.length;i++)
{
cmp="0123456789-";
tst=strTC.substring(i,i+1);
temp = temp + "*" + tst;
if (cmp.indexOf(tst)<0)
{
flg++;
}
}
if (flg!=0)
{
return(false);
}
return(true);
}function valDate(M, D, Y)
{
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(dateField)
{
cDate = dateField.value;
dSize = cDate.length;
aCount = 0;
bCount = 0;
cCount = 0;

if(cDate=='' || dSize==0) 
{
alert("请输入日期!");
dateField.focus();
return(false);
}
if(!checkT(cDate))
{
alert("输入的日期格式必须是:年-月-日\n例如:2003-1-1");
dateField.focus();
return(false);
}
for(var i=0; i < dSize; i++)
{
(cDate.substr(i,1) == "-") ? aCount++ : aCount;
}
if ((aCount != 2))
{
alert("输入的日期格式必须是:年-月-日\n例如:2003-1-1");
dateField.focus();
return(false);
}

//将输入的日期字符串分隔成3部分 (Month, Day & Year
idxBar1 = cDate.indexOf("-");
idxBar2= cDate.lastIndexOf("-");
strM = cDate.substring(idxBar1+1,idxBar2);
strD = cDate.substring(idxBar2+1,dSize);
strY = cDate.substring(0,idxBar1);
//alert("strY = "+strY+"\nstrM = "+strM+"\nstrD = "+strD);

//检测输入的年份是2位数还是4位数;
ySize = strY.length
if(ySize!=2 && ySize!=4 )
{
alert('您输入的日期错误 !');
dateField.focus();
return false;
}

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);
dateField.value = strY+'-'+strM+'-'+strD

ok = valDate(strM, strD, strY);
if(ok==false)

alert("您输入的日期错误 !");
dateField.focus();
return false;
}
}

解决方案 »

  1.   

    if (document.mainForm.joindate.value!="")
      {
         var re=/\d{4}-\d{1,2}-\d{1,2}/;
         if( !re.test(document.mainForm.joindate.value))
         {
             alert("日期格式必须为YYYY-MM-DD!");
             document.mainForm.joindate.focus();
             return false;
         }
      }  if (document.mainForm.ipaddress.value!="")
      {
         var re=/\d{1,2,3}.\d{1,2,3}.\d{1,2,3}.\d{1,2,3}/;
         if( !re.test(document.mainForm.ipaddress.value))
         {
             alert("ip地址格式必须为ddd.ddd.ddd.ddd!");
             document.mainForm.ipaddress.focus();
             return false;
         }
      }