使用javascript+正则表达式判断输入日期是否为yyyy-mm-dd

<html>
  <head>
   <script>
//函数名:CheckDateTime  
//功能介绍:检查是否为日期时间 
function validate(str){ 

    if(!/^19\d\d-[0-1]\d-[0-3]\d+$/.test(form.birth.value)&&!/^20\d\d-[0-1]\d-[0-3]\d+$/.test(form.birth.value)){
        alert("wrong");
  return false;
     }
  else{
    alert("right");
    return true;
  }
}

</script>

  </head>
  <body>
    <form name="form" onsubmit="return validate(this.birth.value);">
   <input type="text" name="birth"/>
   <input type="submit" value="submit"/>
 </form>
  </body>
</html>

 

 

<html>
  <head>
   <script>
//函数名:CheckDateTime  
//功能介绍:检查是否为日期时间 
function validate(str){ 

     var reg = /^(\d+)-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/; 
 
    var r = str.match(reg); 
    if(r==null) {alert("wrong");return false}; 
    r[2]=r[2]-1; 
    var d= new Date(r[1], r[2],r[3], r[4],r[5], r[6]); 

    if(d.getFullYear()!=r[1]){alert("wrong");return false}; 
    if(d.getMonth()!=r[2]){alert("wrong");return false}; 
    if(d.getDate()!=r[3]){alert("wrong");return false}; 
    if(d.getHours()!=r[4]){alert("wrong");return false}; 
    if(d.getMinutes()!=r[5]){alert("wrong");return false}; 
    if(d.getSeconds()!=r[6]){alert("wrong");return false}; 
    alert("right");return false;
}

</script>

  </head>
  <body>
    <form name="form" onsubmit="return validate(this.birth.value);">
   <input type="text" name="birth"/>
   <input type="submit" value="submit"/>
 </form>
  </body>
</html>



你可能感兴趣的:(JavaScript,html,正则表达式)