通过正则表达式验证日期JS代码

前端之家收集整理的这篇文章主要介绍了通过正则表达式验证日期JS代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在网页设计内,使用正则表达式进行字符验证是常有的事,本代码就使用正则表达式进行输入日期的验证,输入错误的时候会弹出提示:“您输入的结止日期不正确!请注意日期格式(如:2007/07/17或2007-07-17)或闰年1,在JavaScript中,正则表达式只能使用"/"开头和结束,不能使用双引号。

<html>
<head>
<title>通过正则表达式验证日期</title>
<Meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<script language="javascript">
function CheckDate(str){
 //在JavaScript中,正则表达式只能使用"/"开头和结束,不能使用双引号
var Expression=/^((((1[6-9]|[2-9]\d)\d{2})(\/|\-)(0?[13578]|1[02])(\/|\-)(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})(\/|\-)(0?[13456789]|1[012])(\/|\-)(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})(\/|\-)0?2(\/|\-)(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$/; 
	var objExp=new RegExp(Expression);
	if(objExp.test(str)==true){
		return true;
	}else{
		return false;
	}
}
function check(myform){
	if(myform.sDate.value==""){
		alert("请输入开始日期");myform.sDate.focus();return;
	}		
	if(!CheckDate(myform.sDate.value)){
		alert("您输入的开始日期不正确!\n请注意日期格式(如:2007/07/17或2007-07-17)或闰年!");myform.sDate.focus();return;
	}
	if(myform.eDate.value==""){
		alert("请输入结止日期");myform.eDate.focus();return;
	}		
	if(!CheckDate(myform.eDate.value)){
		alert("您输入的结止日期不正确!\n请注意日期格式(如:2007/07/17或2007-07-17)或闰年!");myform.eDate.focus();return;
	}
	myform.submit();
}
</script>
<body><form name="form1" method="post" action="">
<table width="608" height="82"  border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td valign="top"><table width="100%" height="62"  border="0" cellpadding="0" cellspacing="0">
      <tr>
        <td height="39" colspan="2" align="center" class="word_white">正则表达式验证日期</td>
      </tr>
      <tr>
        <td width="17%">&nbsp;</td>
        <td width="83%">从<input name="sDate" type="text" id="sDate">
&nbsp;到&nbsp; <input name="eDate" type="text" id="eDate">&nbsp;<input name="Button" type="button" class="btn_grey" value="查询" onClick="check(form1)"></td>
      </tr>
    </table></td>
  </tr>
</table></form>
</body>
</html>
原文链接:https://www.f2er.com/regex/359912.html

猜你在找的正则表达式相关文章