Click here to Skip to main content
15,885,032 members
Articles / Programming Languages / Javascript

Validate time using JavaScript

Rate me:
Please Sign up or sign in to vote.
4.00/5 (5 votes)
9 Nov 2006CPOL 117.5K   634   5   4
Solution to validate your time using JavaScript.

Introduction

I have read a lot of articles on time validation in a web based application, but could not get my kind of solution. My requirement was to write any string as time and the program should be intelligent enough to validate it. For instance, if the user type 1:4 5 AM (which should be 1:45 AM), the code should validate and correct it by removing the additional space. Not only that, my sample application checks for valid hour, minute, and AM/PM as well, and takes time format as (HH:MM AM/PM).

Code Explanation

Create a sample ASP.NET application and add a .NET TextBox control and a client-side button. The OnClick of the button will call the validatetime() method.

ASP.NET
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<input type="button" value="validate time" onclick="validatetime()">

The validatetime() JavaScript method will internally call two other functions: trimAllSpace() and trimString().

JavaScript
function  validatetime()
{
  var strval = document.Form1.TextBox1.value;
  var strval1;
    
  //minimum lenght is 6. example 1:2 AM
  if(strval.length < 6)
  {
   alert("Invalid time. Time format should be HH:MM AM/PM.");
   return false;
  }
  
  //Maximum length is 8. example 10:45 AM
  if(strval.lenght > 8)
  {
   alert("invalid time. Time format should be HH:MM AM/PM.");
   return false;
  }
  
  //Removing all space
  strval = trimAllSpace(strval); 
  
  //Checking AM/PM
  if(strval.charAt(strval.length - 1) != "M" && strval.charAt(
      strval.length - 1) != "m")
  {
   alert("Invalid time. Time shoule be end with AM or PM.");
   return false;
   
  }
  else if(strval.charAt(strval.length - 2) != 'A' && strval.charAt(
      strval.length - 2) != 'a' && strval.charAt(
      strval.length - 2) != 'p' && strval.charAt(strval.length - 2) != 'P')
  {
   alert("Invalid time. Time shoule be end with AM or PM.");
   return false;
   
  }
  
  //Give one space before AM/PM
  
  strval1 =  strval.substring(0,strval.length - 2);
  strval1 = strval1 + ' ' + strval.substring(strval.length - 2,strval.length)
  
  strval = strval1;
      
  var pos1 = strval.indexOf(':');
  document.Form1.TextBox1.value = strval;
  
  if(pos1 < 0 )
  {
   alert("invlalid time. A color(:) is missing between hour and minute.");
   return false;
  }
  else if(pos1 > 2 || pos1 < 1)
  {
   alert("invalid time. Time format should be HH:MM AM/PM.");
   return false;
  }
  
  //Checking hours
  var horval =  trimString(strval.substring(0,pos1));
   
  if(horval == -100)
  {
   alert("Invalid time. Hour should contain only integer value (0-11).");
   return false;
  }
      
  if(horval > 12)
  {
   alert("invalid time. Hour can not be greater that 12.");
   return false;
  }
  else if(horval < 0)
  {
   alert("Invalid time. Hour can not be hours less than 0.");
   return false;
  }
  //Completes checking hours.
  
  //Checking minutes.
  var minval =  trimString(strval.substring(pos1+1,pos1 + 3));
  
  if(minval == -100)
  {
   alert("Invalid time. Minute should have only integer value (0-59).");
   return false;
  }
    
  if(minval > 59)
  {
     alert("Invalid time. Minute can not be more than 59.");
     return false;
  }   
  else if(minval < 0)
  {
   alert("Invalid time. Minute can not be less than 0.");
   return false;
  }
   
  //Checking minutes completed.
  
  //Checking one space after the mintues 
  minpos = pos1 + minval.length + 1;
  if(strval.charAt(minpos) != ' ')
  {
   alert("Invalid time. Space missing after minute. 
       Time should have HH:MM AM/PM format.");
   return false;
  }
 
  return true;
}

Here is the trimAllSpace() function:

JavaScript
function trimAllSpace(str) 
{ 
    var str1 = ''; 
    var i = 0; 
    while(i != str.length) 
    { 
        if(str.charAt(i) != ' ') 
            str1 = str1 + str.charAt(i); i ++; 
    } 
    return str1; 
}

Here is the trimString() function:

JavaScript
function trimString(str) 
{ 
     var str1 = ''; 
     var i = 0; 
     while ( i != str.length) 
     { 
         if(str.charAt(i) != ' ') str1 = str1 + str.charAt(i); i++; 
     }
     var retval = IsNumeric(str1); 
     if(retval == false) 
         return -100; 
     else 
         return str1; 
}

The IsNumeric() function will check whether the user has entered a numeric value or not.

JavaScript
function IsNumeric(strString) 
{ 
    var strValidChars = "0123456789"; 
    var strChar; 
    var blnResult = true; 
    //var strSequence = document.frmQuestionDetail.txtSequence.value; 
    //test strString consists of valid characters listed above 
    if (strString.length == 0) 
        return false; 
    for (i = 0; i < strString.length && blnResult == true; i++) 
    { 
        strChar = strString.charAt(i); 
        if (strValidChars.indexOf(strChar) == -1) 
        { 
            blnResult = false; 
        } 
     }
     return blnResult; 
}

That is all. There is nothing much to explain about the above code blocks. Every line of code is really simple.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
India India
Working with Logica Pvt. Ltd as a Tech Lead.

Comments and Discussions

 
QuestionSimple script Pin
easydeepan30-Jan-13 9:42
easydeepan30-Jan-13 9:42 
GeneralMy vote of 2 Pin
jamwal30-Sep-09 10:15
jamwal30-Sep-09 10:15 
GeneralRegEx Pin
mcmurrym11-Jul-08 15:41
mcmurrym11-Jul-08 15:41 
GeneralSource code missing Pin
TBermudez10-Nov-06 12:20
TBermudez10-Nov-06 12:20 
The source code link is broken.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.