<script language="JavaScript">
<!--
/*
Check this string is a Date or not
Format:2002.9.20,2002-9-20 or 2002/9/20
Ex:alert("2003.9.20".isDate())
*/
String.prototype.isDate=function(){
var re=/^(\d{1,4})(-|\/|\.)(\d{1,2})\2(\d{1,2})$/;
var r=this.match(re)
if(r==null)return "h"
var d=new Date(r[1],r[3]-1,r[4])
return (d.getFullYear()==r[1]&&d.getMonth()==r[3]-1&&d.getDate()==r[4])
}
alert("2000-2-30".isDate())
alert("2000-2-28".isDate())//-->
</script>

解决方案 »

  1.   

    <script language=javascript>
    //  怎么判断客户端输入的年、月、日是否合法? 
    function strDateTime(str)
    {
       var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{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]);
    }
    alert(strDateTime("2002-01-31"));
    alert(strDateTime("2002-01-41"));
    </script>
      

  2.   

    //判断客户端输入的年、月、日是否合法,方法2
    function CheckIsDate(value)//格式为yyyy-mm-dd
    {
    var strValue  = new String();

    var year = new String();
    var month = new String();
    var day = new String();
    strValue = value;

    if (strValue.length!=10)

    return false;
    }  
    else 
    if (strValue.charAt(4)!='-'||strValue.charAt(7)!='-')
    {
    return false;
    }
    else

    year = strValue.substr(0,4);
    month = strValue.substr(5,2);
    month = month-1; 
    day = strValue.substr(8,2);

    var testDate = new Date(year,month,day)
    //alert(testDate);
    return  (year == testDate.getFullYear()) && (month ==testDate.getMonth())&&(day == testDate.getDate());
    }   
      return true;
    }
    alert(CheckIsDate("2002-02-31"));
    alert(CheckIsDate("2002-04-31"));
    </script>
      

  3.   

    <form method=post action="" name="form1">
    <input type="text" name="keyWord" onchange="vbscript:msgbox(isdate(document.form1.keyWord.value))">
    </form>