js验证日期格式 JavaScript判断时间格式正确
方法一:JS:
<script language="javascript">
function check(){
var a = /^(\d{4})-(\d{2})-(\d{2})$/
if (!a.test(document.getElementById("TextBox1").value)) {
alert("日期格式不正确!")
return false
}
else
return true
}
</script>
HTML:
<div>
<asp:TextBox ID="TextBox1" runat="server" onblur="check();"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
</div>
上面的方法是验证YYYY-MM-DD日期格式,不能验证“2012-11-45”之类的不正确的日期
方法二:
JS:正则表达式判断日期格式
<script type="text/javascript"> function check() { alert("sss");
var date = document.getElementById("TextBox1").value;
var result = date.match(/((^((1[8-9]\d{2})|([2-9]\d{3}))(-)(10|12|0?[13578])(-)(3[01]|[12][0-9]|0?[1-9])$)|(^((1[8-9]\d{2})|([2-9]\d{3}))(-)(11|0?[469])(-)(30|[12][0-9]|0?[1-9])$)|(^((1[8-9]\d{2})|([2-9]\d{3}))(-)(0?2)(-)(2[0-8]|1[0-9]|0?[1-9])$)|(^([2468][048]00)(-)(0?2)(-)(29)$)|(^([3579][26]00)(-)(0?2)(-)(29)$)|(^([1][89][0][48])(-)(0?2)(-)(29)$)|(^([2-9][0-9][0][48])(-)(0?2)(-)(29)$)|(^([1][89][2468][048])(-)(0?2)(-)(29)$)|(^([2-9][0-9][2468][048])(-)(0?2)(-)(29)$)|(^([1][89][13579][26])(-)(0?2)(-)(29)$)|(^([2-9][0-9][13579][26])(-)(0?2)(-)(29)$))/);
if(result==null) {
alert("请输入正确的日期格式"); return false;
}}
</script>
<div>
<asp:TextBox ID="TextBox1" runat="server" onblur="check();"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
</div>
补充一个方法,方法三:
JS
function RQcheck(RQ) {
var date = RQ;
var result = date.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
if (result == null)
return false;
var d = new Date(result[1], result[3] - 1, result[4]);
return (d.getFullYear() == result[1] && (d.getMonth() + 1) == result[3] && d.getDate() == result[4]);
}
function CheckAdd() {
var ret = true;
if (!RQcheck($id("txt_LLRQ").value)) {
alert("请输入易做图正确的日期");
return false;
}
return ret;
}