Solved

Javascript to check valid time is entered into a form

Posted on 2013-11-07
9
1,086 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
9 Comments
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39630231
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 33

Assisted Solution

by:Big Monty
Big Monty earned 200 total points
ID: 39630311
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 110

Expert Comment

by:Ray Paseur
ID: 39630914
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:EICT
ID: 39642173
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 110

Accepted Solution

by:
Ray Paseur earned 200 total points
ID: 39642654
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 43

Expert Comment

by:Rob
ID: 39699175
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 33

Expert Comment

by:Big Monty
ID: 39699176
we both provided adequate solutions, why not split?
0

Featured Post

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
phpmyadmin memory error 55 92
Need help for active menu class depending of the page 4 28
SSL unsecure page mystery 17 46
replacate wordpress websites 3 23
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

734 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