Solved

Javascript to check valid time is entered into a form

Posted on 2013-11-07
9
1,062 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 109

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 109

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
Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

 

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 109

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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

This article discusses how to create an extensible mechanism for linked drop downs.
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
The viewer will learn the basics of jQuery, including how to invoke it on a web page. 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.: (CODE)
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

856 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