一段简单 javascript 的代码,用来验证日期的格式,支持闰年,支持 IE、Fixfox、Chrome 等主流浏览器
提示,日期格式必须是:yyyy-MM-dd
大家可以用 my97DatePicker 日期控件,该控件默认的格式就是:yyyy-MM-dd
贴出代码:
<html>
<head>
<script type="text/javascript">
function CheckDate(dateValue)
{
var reg=/^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$/;
return reg.test(dateValue); // 或者 dateValue.match(reg);
}
function ValidateBirthday()
{
var txtBirthday = document.getElementById("txtBirthday");
var birthdayErrorContainer = document.getElementById("birthdayErrorContainer");
birthdayErrorContainer.style.color = "black";
birthdayErrorContainer.innerHTML = "";
if(CheckDate(txtBirthday.value))
{
birthdayErrorContainer.style.color = "green";
birthdayErrorContainer.innerHTML = "日期正确!";
return true;
}
else
{
birthdayErrorContainer.style.color = "red";
birthdayErrorContainer.innerHTML = "日期不合法,请重新输入!";
return false;
}
}
function ValidateForm()
{
if(!ValidateBirthday())
{
alert("日期不正确!");
return false;
}
return true;
}
</script>
</head>
<body>
<form action="http://www.baidu.com" method="post" id="myForm" onsubmit="return ValidateForm();">
请输入日期(日期格式如:2010-05-08):<input type="text" name="txtBirthday" id="txtBirthday" onblur="ValidateBirthday();"><span id="birthdayErrorContainer"></span><br/>
<input type="submit" value="提交">
</form>
</body>
</html>
轉載來自:http://www.cnblogs.com/Music/archive/2011/08/16/validate-true-date-formatter-with-javascript.html