[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

PHP Date Validation

Posted on 2011-05-02
12
Medium Priority
?
340 Views
Last Modified: 2012-05-11
Hi,

I am new to PHP and I am trying to get the code below from http://smartwebby.com/PHP/datevalidation.asp to work but kept getting the following error:

Deprecated: Function ereg() is deprecated in C:\xampp\htdocs\shopfloordb\date.php on line 26

Deprecated: Function ereg() is deprecated in C:\xampp\htdocs\shopfloordb\date.php on line 34

Deprecated: Function ereg() is deprecated in C:\xampp\htdocs\shopfloordb\date.php on line 38

You help in getting this code to work is appreciated.

Thank you


<?php
//Check whether the submission is made
if(!isset($_POST["hidSubmit"])){

//Declarate the necessary variables 
$strdate="";
$strdate1="";
DisplayForm();
}
else{
$strdate=$_POST["txtdate22"];

//Check the length of the entered Date value 
if((strlen($strdate)<10)OR(strlen($strdate)>10)){
echo("Enter the date in 'dd/mm/yyyy' format");
}
else{

//The entered value is checked for proper Date format 
if((substr_count($strdate,"/"))<>2){
echo("Enter the date in 'dd/mm/yyyy' format");
}
else{
$pos=strpos($strdate,"/");
$date=substr($strdate,0,($pos));
$result=ereg("^[0-9]+$",$date,$trashed);
if(!($result)){echo "Enter a Valid Date";}
else{
if(($date<=0)OR($date>31)){echo "Enter a Valid Date";}
}
$month=substr($strdate,($pos+1),($pos));
if(($month<=0)OR($month>12)){echo "Enter a Valid Month";}
else{
$result=ereg("^[0-9]+$",$month,$trashed);
if(!($result)){echo "Enter a Valid Month";}
}
$year=substr($strdate,($pos+4),strlen($strdate));
$result=ereg("^[0-9]+$",$year,$trashed);
if(!($result)){echo "Enter a Valid year";}
else{
if(($year<1900)OR($year>2200)){echo "Enter a year between 1900-2200";}
}
}
}
DisplayForm();
}

//User-defined Function to display the form in case of Error
function DisplayForm(){
global $strdate;
?>

<form name="form1" method="post" action="">
<table width="50%"  border="1" align="center" cellpadding="0" cellspacing="0" bgcolor="#DEE3ED">
<tr>
<td width="43%" align="right" class="text">Enter Date 
<td width="57%"><input name="txtdate22" type="text" id="txtdate22" value="<?php echo $strdate; ?>" />
<span class="date">*(mm/dd/yyyy)
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="Submit22" value="Submit" />
<input type="hidden" name="hidSubmit" value="true">
</tr>
</table>
</form>
<?php
return;
}
?>

Open in new window

0
Comment
Question by:Wayne88
  • 4
  • 3
  • 2
  • +2
11 Comments
 
LVL 15

Expert Comment

by:gplana
ID: 35508453
ereg function is deprecated since php5.3.

try to change ereg by preg_reg.

When you have:
    ereg($patern, $text_string);
change it for:
    preg_match('/'.$pattern.'/', $text_string);

hope it helps. Regards.
0
 
LVL 34

Assisted Solution

by:Beverley Portlock
Beverley Portlock earned 400 total points
ID: 35509005
I would approach it slighlty differently and use the PHP checkdate function http://www.php.net/checkdate

<?php
//Check whether the submission is made
if(!isset($_POST["hidSubmit"])){

     //Declarate the necessary variables
     $strdate="";
     $strdate1="";
     DisplayForm();
}
else{
     $strdate=$_POST["txtdate22"];

     if ( preg_match('#([0-9]{1,2})/([0-9]{1,2})/([0-9]{4})#', trim($strdate), $dateMatch ) > 0 ) {

          // Check if date is valid
          //
          if ( ! checkdate( $dateMatch[2], $dateMatch[1], $dateMatch[3] ) )
               echo "Enter a valid date";
     }
     else
          echo "Enter the date in 'dd/mm/yyyy' format";

     DisplayForm();
}

//User-defined Function to display the form in case of Error
function DisplayForm(){
     global $strdate;
     ?>

<form name="form1" method="post" action="">
<table width="50%" border="1" align="center" cellpadding="0"
    cellspacing="0" bgcolor="#DEE3ED">
    <tr>
        <td width="43%" align="right" class="text">Enter Date
        <td width="57%"><input name="txtdate22" type="text" id="txtdate22"
            value="<?php echo $strdate; ?>" /> <span class="date">*(dd/mm/yyyy)
        </span></td>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center"><input type="submit" name="Submit22"
            value="Submit" /> <input type="hidden" name="hidSubmit" value="true"></td>
    </tr>
</table>
</form>
<?php
return;
}
?>

Open in new window



If you want to add additional validation then $dateMatch[2], $dateMatch[1], $dateMatch[3] provide the month, day and year in the fragment above.
0
 
LVL 12

Expert Comment

by:Mohamed Abowarda
ID: 35510704
The function ereg() is DEPRECATED as of PHP 5.3.0.

You can use the alternative and faster function preg_match():
http://www.php.net/manual/en/function.preg-match.php
0
Technology Partners: 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!

 
LVL 111

Expert Comment

by:Ray Paseur
ID: 35512393
Please read this article over.  It tells how to handle DATETIME strings in PHP and MySQL.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html
0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 600 total points
ID: 35512599
Install this script and run it to see how you can use the PHP built-in functions to handle the date.  But you may be surprised how PHP interprets this:

03/12/2010

That date is ambiguous - it could be March 12 or December 3.  PHP has common-sense rules for dealing with that sort of thing.  I think you will find that mm/dd/yyyy makes more sense.  And I think that dd-mm-yyyy, using hyphens instead of slashes might be a good pattern.

Whenever you are unsure about how a PHP function works (like ereg() in the code snippet above) you can look it up on the PHP.net online man pages!  Check this out:
http://php.net/manual/en/function.ereg.php

The messages you got were not "errors" - they were "deprecated" messages.  Ignore them at your peril, but you can turn them off with this:

error_reporting(E_ALL ^ E_DEPRECATED);

Hope that helps, ~Ray
<?php // RAY_temp_wayne88.php

// USE THIS SETTING WHEN DEBUGGING
error_reporting(E_ALL);

// REQUIRED FOR PHP 5.1+
date_default_timezone_set('America/Chicago');

// INITIALIZE THE VARIABLES
$strdate = NULL;
$errorms = NULL;

// IF ANYTHING IS POSTED RUN THE ACTION SCRIPT
if(!empty($_POST["txtdate22"]))
{
    // MAKE A TIMESTAMP
    $ts = strtotime($_POST["txtdate22"]);

    // StrToTime() RETURNS FALSE ON FAILURE
    if ($ts === FALSE)
    {
        $errorms = "PLEASE ENTER A VALID DATETIME STRING";
    }

    // StrToTime() RETURNS A UNIX TIMESTAMP ON SUCCESS
    else
    {
        $errorms = "THE DATE IS " . date('r', $ts);
        $strdate = date('d/m/Y', $ts);
        $year = date('Y', $ts);
        if ( ($year < '1900') || ($year > '2200') )
        {
            $errorms .= " BUT THE YEAR IS OUT OF RANGE (1900-2200)";
        }
    }
}

// CREATE THE FORM USING HEREDOC NOTATION
$form = <<<FORM
<form method="post">
$errorms
Enter Date
<input name="txtdate22" type="text" value="$strdate" />
<input type="submit" name="Submit22" value="Submit" />
</form>
FORM;

echo $form;

Open in new window

0
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 35512711
Ray said: "I think you will find that mm/dd/yyyy makes more sense"

Sheesh! Colonials!

C@mon Ray, only YYYY-MM-DD makes sense and we all know it........


;-)


0
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 35512719
C@mon..... hmm pressed SHIFT and got @ rather than '

Silly me.
0
 
LVL 18

Author Comment

by:Wayne88
ID: 35513476
bportlock, I wanted to select your solution as an alternate and award you points but i messed up. not sure how i can give you points now. sorry.
0
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 35513834
I'll request a moderator to reopen it so you can reallocate the points as you wish.

0
 
LVL 18

Author Comment

by:Wayne88
ID: 35514741
sounds good
0
 
LVL 18

Author Closing Comment

by:Wayne88
ID: 35516115
thanks!
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

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…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
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.
Suggested Courses
Course of the Month19 days, 3 hours left to enroll

834 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