- <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){
- hour = textValue.substr(0,2);
- if(!isNum(hour)){
- text.value = '00';
- return;
- }
- if(hour < 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{
- 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)
- {
- if(58==e.keyCode) {return true;}
- keynum = e.keyCode
- }else if(e.which)
- {
- 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>
|