[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1144
  • Last Modified:

Javascript to check valid time is entered into a form

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
EICT
Asked:
EICT
2 Solutions
 
Ray PaseurCommented:
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
 
Big MontySenior Web Developer / CEO of ExchangeTree.org Commented:
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
 
Ray PaseurCommented:
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
EICTAuthor Commented:
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
 
Ray PaseurCommented:
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
 
RobOwner (Aidellio)Commented:
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
 
Big MontySenior Web Developer / CEO of ExchangeTree.org Commented:
we both provided adequate solutions, why not split?
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now