js验证日期格式
下面介绍两种JS验证的方式:
方法一:
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> |
HTML:
<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; }
此方法实现效果和方法二相同
相关推荐
88274956 2020-11-03
runner 2020-09-01
梦的天空 2020-08-25
移动开发与培训 2020-08-16
ReunionIsland 2020-08-16
lyqdanang 2020-08-16
MyNameIsXiaoLai 2020-07-08
星辰的笔记 2020-07-04
csstpeixun 2020-06-28
letheashura 2020-06-26
liaoxuewu 2020-06-26
sunzhihaofuture 2020-06-21
FEvivi 2020-06-16
坚持着执着 2020-06-16
waterv 2020-06-14
xiaoge00 2020-06-14
firejq 2020-06-14
firstboy0 2020-06-14
e度空间 2020-06-12
zhongweinan 2020-06-10