Solved

Javascript to check valid time is entered into a form

Posted on 2013-11-07
9
1,036 Views
Last Modified: 2013-12-14
Hi,

I have the following piece of PHP which validates a PHP form to check that the start and end times entered in the form are valid.  This PHP check is done on a second process page but I would like to replace it with a JavaScript.  Please can someone write me a piece of JavaScript which does a similar check that valid start and end times are entered in the form and that the end time follows the start.

Thank you.

////////////CHECK TIMES ARE VALID/////////////////////////
 
 
       $stime_hr = trim($_POST['starttime_hr']);
       $etime_hr = trim($_POST['endtime_hr']);
       $stime_min = trim($_POST['starttime_min']);
       $etime_min = trim($_POST['endtime_min']);
      
      //1. first check times are valid 24hr values
   if (($stime_hr>='00' && $stime_hr<='24') AND
   ($etime_hr>='00' && $etime_hr<='24') AND
   ($stime_min>='00' && $stime_min<='59') AND
   ($etime_min>='00' && $etime_min<='59'))
   {


  $newstart=$stime_hr.':'.$stime_min.':00';
  $newend=$etime_hr.':'.$etime_min.':00';



  //2. The check end time follows start time
   
  if (($stime_hr==$etime_hr && $stime_min>$etime_min) OR ($stime_hr>$etime_hr))
    {$errors[] = 'The End Time enterred does not follow the Start Time';}
     
   
   
   } else {$errors[] = 'You have entered an invalid Start Time or End Time';}
 
  /////////////End of Time check/////////////////////////
0
Comment
Question by:EICT
9 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Programmers often overthink DATETIME calculations.  I may be able to look at this more later today, but for now you might want to read this article and see how easy PHP makes some of this.  
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html

A sensible design might be to use AJAX requests to validate the times on the server.

Best regards, ~Ray
0
 
LVL 32

Assisted Solution

by:Big Monty
Big Monty earned 200 total points
Comment Utility
agree with Ray, checking it server side would be best, since PHP can handle that quite easily. However, if  you're using HTML5, you can use the pattern attribute:

<input type="text" pattern="([01]?[0-9]|2[0-3])(:[0-5][0-9]){2}"
    required="required" placeholder="hh:mm:ss" />

fiddle: http://jsfiddle.net/ult_combo/6uwFp/

or if you're using the jQuery validator plugin, you could add a custom method to it:

$.validator.addMethod("time24", function(value, element) {
    if (!/^\d{2}:\d{2}:\d{2}$/.test(value)) return false;
    var parts = value.split(':');
    if (parts[0] > 23 || parts[1] > 59 || parts[2] > 59) return false;
    return true;
}, "Invalid time format.");

fiddle: http://jsfiddle.net/ult_combo/UPjqf/1/
docs: http://docs.jquery.com/Plugins/Validation/Validator/addMethod#examples
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Agree with The Big Daddy -- both of those methods make sense to me.

There is nothing you can write (easily) in JS or HTML5 that will come close to the functionality of PHP strtotime() and date(), two functions that play together in ways that are nearly magical.  And since you're going to have to do the validation on the server anyway, you might as well know how it's done in PHP.  The reason for server side validation is to protect your data model.  Hackers will not bother to play nicely with your JavaScript -- they will bypass that entirely and post toxic data directly into the request, so your server-side script needs to be able to recognize acceptable data and only accept good values.  This is necessary no matter what kind of client interface you choose.  The JavaScript is there to make the site work nicely for humans, but it's not useful as a security measure.
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

Author Comment

by:EICT
Comment Utility
Thanks for your comments. Sorry I have not replied sooner, I was doing more pressing work.

I will look at the link etc and reply in more detail tomorrow.

I had planned to use both client side and server side validation so that the user could correct the time entered in the form before it was submitted.

Speak soon.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 200 total points
Comment Utility
Try this part on the client side.
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<title>Ajax Example Using jQuery (EICT)</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

<script>
$(document).ready(function(){
    $("#xinput").blur(function(){
        indata = $("#xinput").val();
        $.get("RAY_temp_eict_server.php", {dt:indata}, function(response){
            $("#output p#target").html(response);
            if (response == "Date/Time is invalid"){
                $("#xinput").val('');
                $("#xinput").focus();
            }
        });
    });
});
</script>

</head>
<body>

<input id="xinput" placeholder="Enter a DateTime Value" />
<input type="button" />
<div   id="output">
   <p  id="target">This element gets the AJAX response</p>
</div>

</body>
</html>

Open in new window

And this part on the server.
<?php // RAY_temp_eict_server.php
error_reporting(E_ALL);

// CHOOSE A ZONE THAT MAKES SENSE FOR YOUR WORK
date_default_timezone_set('America/Chicago');

// PROCESS THE GET-METHOD REQUEST
$dt = (!empty($_GET['dt'])) ? strtotime($_GET['dt']) : FALSE;

// IF WE CANNOT GET A VALID TIMESTAMP
if (!$dt) die('Date/Time is invalid');

// RETURN A PRETTY DATETIME FOR CLIENT DISPLAY
$datex = date('g:i a (T), l, F jS, Y', $dt);
die($datex);

Open in new window

HTH, ~Ray
0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
Comment Utility
I've requested that this question be closed as follows:

Accepted answer: 400 points for Ray_Paseur's comment #a39642654

for the following reason:

This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.
0
 
LVL 32

Expert Comment

by:Big Monty
Comment Utility
we both provided adequate solutions, why not split?
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

There are a couple ways to attach a JavaScript function to dynamically created elements. You can make a new script for each element as it’s created or you can use delegation. Delegation allows a single script that is added at page creation to mat…
How to build a simple, quick and effective accordion menu using just 15 lines of jQuery and 2 css classes
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now