時間入力チェック

3920 ワード



<html>
<head>
    <title>       --    </title>
    <!-- 2009.12.12        -->
</head>
<body>
                   <br/>
                 :           <br/>
          <input type="text" onblur="isTimeFormat(this)" onkeyup="verify(this)" onkeypress="return inputNumber(event,this);"  title="    :00:00"/>
          <br/>
</body>
</html>

<script>
   //            
   function isTimeFormat(str) {
      var a = str.value.match(/^([0-2][0-9]):([w0-5][0-9])$/);
      if (a == null) {
         alert("      ,       ,   。");
         var length=str.value.length;
         if (length==1) {str.value="0" + str.value +":00";}
         else if (length==2) {str.value+=":00";}
         else if (length==3) {str.value+="00";}
         else if (length==4) {str.value+="0";}
         else {str.value="00:00";}
         str.select();
         return false;
      }
      return true;
   }   
   //       
   function verify(text){
    var hour;
    var minute;
    var tmp;
    var index;
    var textValue = text.value;
    if(textValue.length == 1 ) {
      if (textValue == ":"){text.value = "00:"; }
      return true;
    }
    if(textValue.length == 2 ) {
      if (!isNum(textValue)) text.value = "0" + textValue;
      return true;
    }
    if(textValue.length > 2){ //     2 ,    
        hour = textValue.substr(0,2); //      ,   
        if(!isNum(hour)){//    
            text.value = '00';
            return;
        }
        if(hour < 24){ //10<x<24
           text.value = hour + ':';//    
           index = textValue.indexOf(':'); //    
           minute = index > 0 ? textValue.substr(index + 1,2) : textValue.substr(2,2);
           if(!isNum(minute)){//    
                text.value = hour + ':00';
                return;
            }
           if(minute < 59){
            tmp = hour + ':' + minute;
           }else{
            tmp = hour + ':59';
           }
        }else{ //x>=24
           hour = '0' + textValue.substr(0,1);
           text.value = hour + ':' + text.value.substr(1,1);
           index = textValue.indexOf(':');
           minute = index > 0 ? textValue.substr(index + 1,2) : textValue.substr(1,2);
           if(!isNum(minute)){//    
                text.value = hour + ':00';
                return;
            }
           if(minute < 59){
             tmp = hour + ':' + minute;
           }else{
             tmp = hour + ':59';
           }
        }
    text.value = tmp;//  “  :  ”  
    }
   }
   //       :
   function inputNumber(e,textValue){
    var keynum;
    var keychar;
    var numcheck;
    if(window.event) // IE
    {
        if(58==e.keyCode) {return true;}
        keynum = e.keyCode
    }else if(e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which
    }
    keychar = String.fromCharCode(keynum);
    return isNum(keychar);
   }
   //     
   function isNum(str){
    if(""==str){
      return true;
    }
    var reg = /\D/; 
    return str.match(reg)==null;
   }
   //            
</script>