PHP Date Validation

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

LVL 19
Wayne88Asked:
Who is Participating?
 
Ray PaseurConnect With a Mentor Commented:
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
 
gplanaCommented:
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
 
Beverley PortlockConnect With a Mentor Commented:
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
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
Mohamed AbowardaSoftware EngineerCommented:
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
 
Ray PaseurCommented:
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
 
Beverley PortlockCommented:
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
 
Beverley PortlockCommented:
C@mon..... hmm pressed SHIFT and got @ rather than '

Silly me.
0
 
Wayne88Author Commented:
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
 
Beverley PortlockCommented:
I'll request a moderator to reopen it so you can reallocate the points as you wish.

0
 
Wayne88Author Commented:
sounds good
0
 
Wayne88Author Commented:
thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.