Formatting & Validating Time using Javascript

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

Post Reply
User avatar
christian_phpbeginner
Forum Contributor
Posts: 136
Joined: Sat Jun 03, 2006 2:43 pm
Location: Java

Formatting & Validating Time using Javascript

Post by christian_phpbeginner »

So, I have been working with Javascript lately, and I created a function that formats the time into HH:MM AM/PM. Below is the function, any critique on the code or maybe someone can make it simpler, I would really appreciate it. And if you're going to use it, please use it. I am glad that it might be helpful for others too.

Explanation:

function formatTime will format time to be 09:00 AM, but in order to achieve this, the user must enter 0900, the user has to be specific in their entry....because 9 o'clock could mean 09:45, or even 09:59 !

function AMPM() will decide if it's am or pm, based on the user's entry. If the user has entered 0700, it will display as ouput: 07:00 AM, and if 1900, it will display as 19:00 PM. Function AMPM() would also alert errors if the user accidentally entered for example 25 as the hours.

function checkHours() will validates user entry on hours. There can't be more than 24 hours, nor less than 0 ? For example, if the user entered 25, it will display an error, then force the user to edit the hour again. And if the user has entered 24, it will automatically formatted as 00, and this happens at line:

Code: Select all

else if (h == 24) {...}
function checkMinutes() will validates user entry on minutes. There can't be more than 60 minutes, nor less than 0. Now, it does work when the user enters 19115...it will display an error telling that there are NO MINUTES MORE THAN 60, which in this case is 115 and it's more than 60. But, when the users entered 19000....the program would just ignore it and assumes that it's correct! In order to prevent this, I added another else if, exactly at this line in checkMinutes():

Code: Select all

else if (m == "000" || m == "0000" || m == "00000" || m == "000000") {...}
That line will prevent users by accidentally input: 19000, or 190000, or 1900000, 19000000.

Note: I have tested it in Firefox, IE, and Netscape, but haven't tested it in OPERA.

Cheers,
Chris

Code: Select all

/**
 * @author: christian_phpbeginner
 * @method name : formatTime
 * @param : formName, fieldName
 * @description :
 *    Function to format time as to be HH:MM AM/PM
 * @see :
 *    This function should be combined with AMPM(), checkHours(), checkMinutes() 
 * @how-to :
 *    1. Specify the formName and fieldName in the parameter
 *    2. Always include the function AMPM(), checkHours(), and checkMinutes()
 *    3. You can customize the error message by changing the variable value msgError
 * @example :
 *    <input type="text" onblur = "javascript:formatTime('yourformname', 'yourfieldname');/>
 */
function formatTime (formName, fieldName) {
	
	var form = window.document.forms[formName];
	
	var input = form.elements[fieldName].value;
	var re = new RegExp ('[0-9]{4}');
	var hours;
	var minutes;
	var formattedInput;
	var msgError = "An Error Has Occured.\n\n" +
	               "What are the causes ?\n\n" +
			       "1. YOU DIDN'T ENTER THE MINUTES:\n" +
			       "    For example:\n" +
			       "    a. If you are about to enter 09:00, please enter: 0900.\n" +
			       "    b. If your are about to enter 19:00, please enter only: 1900.\n" +
			       "    It will be formated automatically.\n\n" +
			       "2. YOU HAVE ENTERED A NON NUMERICAL VALUE: abc, a dot(.) sign, or a colon ( : ) sign\n\n" +
			       "3. YOU MIGHT HAVE ACCIDENTALLY ENTERED TOO MANY ZERO(0)";
	
	var matchInput = input.search(re);
	
	if (matchInput == -1 && input != "") {
	   alert(msgError);
	   form.elements[fieldName].focus();
	   return false;	
	} else if (matchInput != -1) {
		hours = input.substring(0, 2);
		minutes = input.substring(2);
		//checkHours, checkMinutes, and AMPM before being stored in the variable
		formattedInput = checkHours(hours, formName, fieldName) + ":" + checkMinutes(minutes, formName, fieldName) + " " + AMPM(hours, formName, fieldName);
		form.elements[fieldName].value = formattedInput;
		return false;
	}
	return true;	
}

/**
 * @author: christian_phpbeginner
 * @method name : AMPM
 * @param : h, formName, fieldName. h = hours
 * @description :
 *    Function to decide whether it's AM or PM
 * @see :
 *    This function should be combined with formatTime(), checkHours(), checkMinutes() 
 * @how-to :
 *    1. Specify the hours, formName and fieldName in the parameter
 *    2. Always include the function formatTime(), checkHours(), and checkMinutes()
 * @example :
 *    1. In HTML Code: <input type="text" onblur = "javascript:AMPM('hourVariable', 'yourformname', 'yourfieldname');/>
 *    2. Within another function: Please see function formatTime()
 */
function AMPM(h, formName, fieldName) {
  var form = window.document.forms[formName];
	if (h <= 12 && h >= 0){
		return "AM";
	} else if (h >= 12 && h <= 24) {
		return "PM";
	} else if (h < 0) {
		alert("AMPM ERROR: Can't decide AM or PM !!\n\nReason:\n\nThere are no clock less than 0, please re-enter !!");
		form.elements[fieldName].focus();
		return form.elements[fieldName].value = "";
	} else if (h > 24) {
		alert("AMPM ERROR: Can't decide AM or PM !!\n\nReason:\n\nThere are no clock more than 24, please re-enter !!");
		form.elements[fieldName].focus();
		return form.elements[fieldName].value = "";
	}
    return false;
}

/**
 * @author: christian_phpbeginner
 * @method name : checkHours
 * @param : h, formName, fieldName. h = hours
 * @description :
 *    Function to validates hour in order to prevent the hour more than 24, and not less than 0
 * @see :
 *    This function should be combined with AMPM(), formatTime(), checkMinutes() 
 * @how-to :
 *    1. Specify the hours, formName and fieldName in the parameter
 *    2. Always include the function AMPM(), formatTime(), and checkMinutes()
 * @example :
 *    1. In HTML Code: <input type="text" onblur = "javascript:checkHours('hourVariables', 'yourformname', 'yourfieldname');/>
 *    2. Within another function: Please see function formatTime()
 */
function checkHours(h, formName, fieldName) {
  var form = window.document.forms[formName];
	if (h < 0) {
		alert("HOURS ERROR: Can't entry value !\n\nReason:\n\nThere are no clock less than 0, please re-enter !!");
		form.elements[fieldName].focus();
		return form.elements[fieldName].value = "";
	} else if (h > 24) {
		alert("HOURS-ERROR: Can't entry value !\n\nReason:\n\nThere are no hours more than 24, please re-enter !!");
		form.elements[fieldName].focus();
		return form.elements[fieldName].value = "";
	} else if (h == 24) {
		return h = "00";
	} else {
		return h;
	}
}

/**
 * @author: christian_phpbeginner
 * @method name : checkMinutes
 * @param : m, formName, fieldName. m = minutes
 * @description :
 *    Function to validates minutes in order to prevent the minutes more than 60, and not less than 0
 * @see :
 *    This function should be combined with AMPM(), formatTime(), checkHours() 
 * @how-to :
 *    1. Specify the minutes, formName and fieldName in the parameter
 *    2. Always include the function AMPM(), formatTime(), and checkHours()
 * @example :
 *    1. In HTML code:
 *          <input type="text" NAME = "txtExample" onblur = "javascript:checkMinutes('minutesVariable', 'yourformname', 'txtExample');/>
 *    2. Within another function: Please see function formatTime() for an example
 */
function checkMinutes(m, formName, fieldName) {
	var form = window.document.forms[formName];
	if (m > 60) {
		alert("MINUTES-ERROR: Can't entry value !\n\nReason:\n\nThere are no minutes more than 60, please re-enter!!");
		form.elements[fieldName].focus();
		return form.elements[fieldName].value = "";
	} else if (m < 0) {
		alert ("MINUTES-ERROR: Can't entry value !\n\nReason:\n\nThere are no minutes less than 0, please re-enter!!");
		form.elements[fieldName].focus();
		return form.elements[fieldName].value = "";
	} else if (m == "") {
		alert ("MINUTES-ERROR: Can't find value !\n\nReason:\n\No minutes has been entered!!");
		form.elements[fieldName].focus();
		return form.elements[fieldName].value = "";
	} else if (m == "000" || m == "0000" || m == "00000" || m == "000000") {
		alert ("MINUTES-ERROR: Can't entry value !\n\nReason:\n\You might have accidentally entered too many ZEROs(0). Please enter only two ZEROs(0)!!");
		form.elements[fieldName].focus();
		return form.elements[fieldName].value = "";
	} else {
		return m;
	}
}
Last edited by christian_phpbeginner on Fri Sep 22, 2006 1:34 am, edited 1 time in total.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

Have you though about making a Javascript object out of this group of related functions? It might organize them better. Also, can you show some Use Cases? It would be useful to see how you see these functions being used.
(#10850)
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

Yep, this looks extremely unit-testable.
User avatar
christian_phpbeginner
Forum Contributor
Posts: 136
Joined: Sat Jun 03, 2006 2:43 pm
Location: Java

Post by christian_phpbeginner »

arborint wrote:Have you though about making a Javascript object out of this group of related functions? It might organize them better. Also, can you show some Use Cases? It would be useful to see how you see these functions being used.
Hi, thanks for the critique and suggestions so far ! And yes, I do realize that currently those functions are still just a collection, but still they are reuseable in a very simple manner.

And I am agree that I should have made it as an OBJECT formatTime() with methods checkHours(), checkMinutes, and AMPM(), because everyone then could just instantiate formatTime() object and get all the methods they need. But, this is where my issue came (skill issue), I am a beginner in Javascript-ing, if someone would kindly show me how to create an object using Javascript, I would be very happy and I will rewrite the code into Objects.

About the USE CASES ? I don't think a USE CASE for this one is exist....because, to use these functions, just follow this simple steps:
1. Between the <head></head> on your html tag, write <script src ="formattime.js" type="text/javascript" language="javascript"></script>
2. Then in your HTML FORM, and an input of type text:
<form name = "formExample">
<input type = "text" name ="txtExample" onblur="formatTime('formExample','txtExample');" />
</form>


And that's all it takes..

Cheers,
Chris
User avatar
christian_phpbeginner
Forum Contributor
Posts: 136
Joined: Sat Jun 03, 2006 2:43 pm
Location: Java

Rewrite the code with OOP Approach

Post by christian_phpbeginner »

Hi, I have understood how to create an Object within Javascript. I thought I would share. So, I rewrote the code above. But you would need a little tutorial on how to use it, later after this small tutorial, I will give you the rewritten code. But please criticize the code, or criticize whatever I don't realize....thanks !!!

Create a class or an object in Javascript, STEP BY STEP:

Step 1: create a class / an object

Code: Select all

function Person (firstName) {
  //constructor
   this.firstName = firstName;
}
Step 2: adding methods -> Use the prototype keyword in javascript as shown below

Code: Select all

Person.prototype.getFirstName = function () {
   alert (this.firstName);
}
Step 3: Save it as Person.js

Step 4: using the class or object by instantiating it in your HTML Code

A. Using the class directly within the HTML tags

Code: Select all

<html>
   <head> 
      <!----You can't instantiate the class here--->
      <script src = "Person.js" type = "text/javascript"></script>
      <!----But you can instantiate the class here--->
      <script type="text/javascript" language="javascript">
           
            var member = new Person('Christian');
            
      </script>
   </head>
   <body onload ="javascript:member.getFirstName();">
   </body>
</html>
B. Using the class in a function then call the function from the HTML Tags:

Code: Select all

<html>
   <head> 
      <!----You can't instantiate the class here--->
      <script src = "Person.js" type = "text/javascript"></script>
      <!----But you can instantiate the class here--->
      <script type="text/javascript" language="javascript">
           
            var member = new Person('Christian');

            function alertUser() {
               member.getFirstName();
            }
            
      </script>
   </head>
   <body onload ="javascript:alertUser();">
   </body>
</html>
Okay, now the full code of Person.js:

Code: Select all

function Person (firstName) {
      this.firstName = firstName;
   }
   
   Person.prototype.getFirstName = function() {
      alert (this.firstName);
   } 
And here we go, the code that we have been waiting for ! TimeFormatter.js:

A very BIG NOTE: I haven't got a chance to test the rewritten code yet.

Code: Select all

/**
 * @classDescription Class to format time into HH:MM AM/PM
 * @param {String}formName
 */
function TimeFormatter (formName) {
	//constructor
	this.formName = formName;
}
/**
 * @author christian_phpbeginner
 * @method formatTime
 * @param {String}fieldName
 * @description Function to format time as to be HH:MM AM/PM
 * @see This function should be combined with AMPM(), checkHours(), checkMinutes()
 */
TimeFormatter.prototype.formatTime = function (fieldName) {
       
        var form = window.document.forms[this.formName];
       
        var input = form.elements[fieldName].value;
        var re = new RegExp ('[0-9]{4}');
        var hours;
        var minutes;
        var formattedInput;
        var msgError = "An Error Has Occured.\n\n" +
                       "What are the causes ?\n\n" +
                               "1. YOU DIDN'T ENTER THE MINUTES:\n" +
                               "    For example:\n" +
                               "    a. If you are about to enter 09:00, please enter: 0900.\n" +
                               "    b. If your are about to enter 19:00, please enter only: 1900.\n" +
                               "    It will be formated automatically.\n\n" +
                               "2. YOU HAVE ENTERED A NON NUMERICAL VALUE: abc, a dot(.) sign, or a colon ( : ) sign\n\n" +
                               "3. YOU MIGHT HAVE ACCIDENTALLY ENTERED TOO MANY ZERO(0)";
       
        var matchInput = input.search(re);
       
        if (matchInput == -1 && input != "") {
           alert(msgError);
           form.elements[fieldName].focus();
           return false;       
        } else if (matchInput != -1) {
                hours = input.substring(0, 2);
                minutes = input.substring(2);
                //checkHours, checkMinutes, and AMPM before being stored in the variable
                formattedInput = checkHours(hours, formName, fieldName) + ":" + checkMinutes(minutes, formName, fieldName) + " " + AMPM(hours, formName, fieldName);
                form.elements[fieldName].value = formattedInput;
                return false;
        }
        return true;   
}

/**
 * @author: christian_phpbeginner
 * @method AMPM
 * @param {Number}h[h=hours] @param{String}fieldName
 * @description Function to decide whether it's AM or PM
 * @see This function should be combined with formatTime(), checkHours(), checkMinutes()
 */
TimeFormatter.prototype.AMPM = function (h, fieldName) {
  var form = window.document.forms[this.formName];
        if (h <= 12 && h >= 0){
                return "AM";
        } else if (h >= 12 && h <= 24) {
                return "PM";
        } else if (h < 0) {
                alert("AMPM ERROR: Can't decide AM or PM !!\n\nReason:\n\nThere are no clock less than 0, please re-enter !!");
                form.elements[fieldName].focus();
                return form.elements[fieldName].value = "";
        } else if (h > 24) {
                alert("AMPM ERROR: Can't decide AM or PM !!\n\nReason:\n\nThere are no clock more than 24, please re-enter !!");
                form.elements[fieldName].focus();
                return form.elements[fieldName].value = "";
        }
    return false;
}

/**
 * @author christian_phpbeginner
 * @method checkHours
 * @param {Number}h @param {String}fieldName
 * @description Function to validates hour in order to prevent the hour more than 24, and not less than 0
 * @see This function should be combined with AMPM(), formatTime(), checkMinutes()
 */
TimeFormatter.prototype.checkHours = function(h, fieldName) {
  var form = window.document.forms[this.formName];
        if (h < 0) {
                alert("HOURS ERROR: Can't entry value !\n\nReason:\n\nThere are no clock less than 0, please re-enter !!");
                form.elements[fieldName].focus();
                return form.elements[fieldName].value = "";
        } else if (h > 24) {
                alert("HOURS-ERROR: Can't entry value !\n\nReason:\n\nThere are no hours more than 24, please re-enter !!");
                form.elements[fieldName].focus();
                return form.elements[fieldName].value = "";
        } else if (h == 24) {
                return h = "00";
        } else {
                return h;
        }
}

/**
 * @author: christian_phpbeginner
 * @method name : checkMinutes
 * @param {Number}m[minutes] @param {String}fieldName
 * @description :
 *    Function to validates minutes in order to prevent the minutes more than 60, and not less than 0
 * @see :
 *    This function should be combined with AMPM(), formatTime(), checkHours()
 */
TimeFormatter.prototype.checkMinutes = function(m, fieldName) {
        var form = window.document.forms[this.formName];
        if (m > 60) {
                alert("MINUTES-ERROR: Can't entry value !\n\nReason:\n\nThere are no minutes more than 60, please re-enter!!");
                form.elements[fieldName].focus();
                return form.elements[fieldName].value = "";
        } else if (m < 0) {
                alert ("MINUTES-ERROR: Can't entry value !\n\nReason:\n\nThere are no minutes less than 0, please re-enter!!");
                form.elements[fieldName].focus();
                return form.elements[fieldName].value = "";
        } else if (m == "") {
                alert ("MINUTES-ERROR: Can't find value !\n\nReason:\n\No minutes has been entered!!");
                form.elements[fieldName].focus();
                return form.elements[fieldName].value = "";
        } else if (m == "000" || m == "0000" || m == "00000" || m == "000000") {
                alert ("MINUTES-ERROR: Can't entry value !\n\nReason:\n\You might have accidentally entered too many ZEROs(0). Please enter only two ZEROs(0)!!");
                form.elements[fieldName].focus();
                return form.elements[fieldName].value = "";
        } else {
                return m;
        }
}
Cheers,
Chris
Post Reply