<script language="javascript1.2">
function checkvalue()
{
根据你的合法性要求对document.all.date.vaule进行检验的代码.
}
</script>
<form onsubmit="return checkvalue()">
<input type="text" name="date" size="10">
</form>
function checkvalue()
{
根据你的合法性要求对document.all.date.vaule进行检验的代码.
}
</script>
<form onsubmit="return checkvalue()">
<input type="text" name="date" size="10">
</form>
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>
<HTML>
<HEAD>
<TITLE>验证日期格式的字符是否为日期型</TITLE>
</HEAD>
<BODY>
<input type="text" name="datastr" size=20><input type="button" name="test" value="测试" onclick="testdate()">
<script language="javascript">
function testdate() {
if (document.all.datastr.value!="") {
if (isdate(document.all.datastr.value)) {
alert("日期");
} else {
alert("非法日期");
}
}
}
function isdate(datestr) {
var endvalue;
endvalue=true;
datestr=new String(datestr);
//日期必须有分隔符
if (datestr.lastIndexOf("-")==-1 && datestr.lastIndexOf("年")==-1 && datestr.lastIndexOf("\/")==-1 && datestr.lastIndexOf(".")==-1) {
endvalue=false;
} else {
//日期字符的长度不能大于11个字符
if (datestr.length>11) {
endvalue=false;
} else {
//日期数据中所包含的字符只能是指定的定符列表中的字符
allowstrlist="1234567890-.年月/日";
for (i=0;i<datestr.length;i++) {
if (allowstrlist.indexOf(datestr.substr(i,1))==-1) {
endvalue=false;
break;
}
}
//搜索并找到该日期值的间隔符
var labcount,labvalue;
labcount=0;
labvalue="";
allowlablist="年月/日-.";
for (i=0;i<datestr.length;i++) {
if (allowlablist.indexOf(datestr.substr(i,1))!=-1) {
tmpvalue=allowlablist.substr(allowlablist.indexOf(datestr.substr(i,1)),1);
if (labvalue=="" || (labcount!=0 && labvalue!=tmpvalue)) {
labcount=labcount+1;
}
labvalue=tmpvalue;
}
}
//日期中不能有多个标记符
if (labcount>1) {
if (tmpvalue!="月" && tmpvalue!="年" && tmpvalue!="日") {
endvalue=false;
} else {
//年月日必须同时存在
if (datestr.lastIndexOf("年")==-1 || datestr.lastIndexOf("月")==-1 || datestr.lastIndexOf("日")==-1) {
endvalue=false;
}
}
}
if (endvalue) {
//年份判断
if (labvalue=="月" || labvalue=="日") {
labvalue="年";
}
tmpvalue=datestr.substring(0,datestr.indexOf(labvalue));
if (tmpvalue.length>4) {
endvalue=false;
} else {
tmpposition=datestr.indexOf(labvalue)+1;
//月份判断
if (labvalue=="年") {
labvalue="月";
}
tmpvalue=datestr.substring(tmpposition,datestr.indexOf(labvalue,tmpposition));
if (tmpvalue.length>2) {
endvalue=false;
} else {
if (tmpvalue>12) {
endvalue=false;
} else {
//日期判断
tmpposition=datestr.indexOf(labvalue,tmpposition)+1;
if (labvalue=="月") {
labvalue="日";
tmpvalue=datestr.substring(tmpposition,datestr.indexOf(labvalue,tmpposition));
} else {
tmpvalue=datestr.substr(tmpposition);
}
if (tmpvalue.length>2) {
endvalue=false;
} else {
if (tmpvalue>31) {
endvalue=false;
}
}
}
}
}
}
}
}
return(endvalue);
}
</script>
</BODY>
</HTML>