When we consider 12 hours format :
         1. one digit or two digits can exists.
         2. it must be less than or equal to 12 and greater than 0
             Here it is regular expression ::
                                /^([0][0-9]|[0-1][0-2]|[0-9])$/

When we consider 24 hours format :
         1. one digit or two digits can exists.
         2. it must be less than or equal to 24 and greater than 0
             Here it is regular expression ::
                                /^([0][0-9]|[0-2][0-4]|[0-9])$/

Here it is java script function :

    function validateHour(id) {
      var val=document.getElementById(id).value;
      var reg = /^([0][0-9]|[0-1][0-2]|[0-9])$/;
      alert(reg.test(val));
   }


Undo Input Value if its not hour :


function validateHour(id) {
 var val=document.getElementById(id).value;
 var reg = /^([0][0-9]|[0-1][0-2]|[0-9])$/;
 if (reg.test(val)){  
 }
 else {
   var len=val.length;
   document.getElementById(id).value=val.substring(0,len-1);
 }
}

Html Code :

<input id="input1" name="input1" onkeyup="return validateHour('input1');" size="2" maxlength="2" value="00"/>

0 comments:

Blogroll

Follow this blog by Email

Popular Posts