Solved

Javascript to check valid time is entered into a form

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

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 108

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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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 108

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 42

Expert Comment

by:Rob Jurd, EE MVE
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 32

Expert Comment

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

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
object oriented programming comparison 5 52
Apply tab index in forms 6 33
Use a select control to call a javascript function 5 29
datetime in sql 6 22
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to dynamically set the form action using jQuery.

948 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

19 Experts available now in Live!

Get 1:1 Help Now