?
Solved

Validate PHP date

Posted on 2003-03-28
8
Medium Priority
?
175 Views
Last Modified: 2006-11-17
I need a simple code which will validate if date is older date than today and if is in the right format.... like this...

date = now (dd.mm.yy)

If date area is empty....

Error... output your date is empty

If date format is not right (dd.mm.yy)

Error... you must provide date in the right format

If date is older than today....

Error... you cant pick older date than today

If everything is ok.....

Date = RightDate

Else Rightdate = ""

Thanx,

0
Comment
Question by:cabriocabrio
[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
  • 4
  • 3
8 Comments
 
LVL 15

Expert Comment

by:VGR
ID: 8224302
first of all you've txwo solutions : server-side (PHP) or client-side (jscript/javascript)

let's do it PHP-style as you posted this in the PHP area :D
(not tested)

<?
function Delta2Dates($parmax,$parmin) { // en jours
  GLOBAL $dbHost, $dbName, $dbLogin, $dbPassword, $sess_osWin;
  $linkID=mysql_connect("$dbHost","$dbLogin","$dbPassword") or die ("bad connect".mysql_error());
  mysql_select_db($dbName,$linkID) or die ("bad select DB ".mysql_error());
  $query="select to_days('$parmax')-to_days('$parmin') as a;";
  $result=mysql_query($query,$linkID) or die ("bad query deltaDates ".mysql_error());
  $res=mysql_fetch_array($result);
  $locres=$res["a"];
  return $locres;
} // Delta2Dates Integer Function


if (isset($_POST)) { // posted data present
  // get the date submitted
  $locDate=$_POST['FDate'];
  $zarbi=explode('.',$locDate); // no need to typecast for integer comparison, PHP is "intelligent" enough
  // analyse it for validity
  $ok=TRUE;
  $msg="date has to be in the past"; // important default value
  if (($zarbi[0]<=0)or($zarbi[0]>31)) {$msg='day invalid'; $ok=FALSE;} // day invalid
  if (($zarbi[1]<=0)or($zarbi[1]>12)) {$msg='month invalid'; $ok=FALSE;} // month invalid
  if (($zarbi[2]<='70)or($zarbi[0]>31)) {$msg='day invalid'; $ok=FALSE;} // day invalid
  // get now() and compare
  if (strlen($zarbi[2])<4) $zarbi[2]='19'.$zarbi[2]; // constraint
  $transformed=$zarbi[2].'-'.$zarbi[1].'-'.$zarbi[0];
  $today=date("Y-m-d"); // MySql-compatible
  $yourtoday=date("d.m.y"); // your format DD.MM.YY
  $ok=($ok AND (Delta2Dates($today,$transformed)>=0));
  // proceed
  if (! $ok) { // display error line and set default date to today
    echo "error : $msg<BR><BR>";
    $rightDate=$yourtoday;
  } // if not OK
} else { // no posted data, this is first entering :D
  $rightDate='DD.MM.YYYY'; // or whatever default value you want
} // if $_POST set

// here your FORM action=$PHP_SELF method=POST
// with echo "<INPUT type=text name=FDate value=$rightDate>";
?>
0
 
LVL 15

Expert Comment

by:VGR
ID: 8224303
note that you've to provide DB values, of else I've a solution not inviolving the MySql DB (but it would be a shame). In the same spirit, the testing of days between 1 and 31 and month(e)s between 1 and 12 may be replaced by a MySql-check that the date is valid. This would be cleaner.
0
 
LVL 4

Expert Comment

by:bljak
ID: 8229923
bit shorter version without any sql connection needed

$today = getdate();
(int)$today = strtotime($today["mday"]." ".$today["month"]." ".$today["year"]);

/* lets assume you called your textbox "yourdate"
and  you link from some site to this one */

$rightDate = FALSE;

//validate POST method
if(!$_POST["yourdate"]) {
  echo "Your date is empty";
} else {
  //check first of right format valid is dd.mm.yy
  if(!ereg("^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{2}$",$_POST["yourdate"])){
    echo "Error... you must provide date in the right format";
  } else {
    $submitDate = explode(".",$_POST["yourdate"]);
    //lets make sure user doesn't overroll 31 days and 12 months
    if($submitDate[0] > 31 || $submitDate[1] > 12)
    {
      DIE("Invalid Day or Month submitted.");
    }
    (int)$submitDate = mktime(0,0,0,$submitDate[1],$submitDate[0],$submitDate[2]);
    if($submitDate < $today){
      echo "Error... you cant pick older date than today";
    } else {
      //just a 100% reverse check since giving in 31.02.03 exists also
      if(date("d.m.y",$submitDate) != $_POST["yourdate"])
      {
        echo
        DIE("Invalid Timeformat.");
      }
      echo $submitDate."<br>";
      echo "Thank you";
      $rightDate = $_POST["yourdate"];
    }
  }
}

//checked, valid, works
//bljak
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!

 
LVL 4

Accepted Solution

by:
bljak earned 300 total points
ID: 8229928
ah sorry, that echo $submitDate was just for testing purposes, just remove it :)

//bljak
0
 

Author Comment

by:cabriocabrio
ID: 8250761
I had to modify a litle but BIG THANX!

//bljak  you rule ;)
0
 
LVL 15

Expert Comment

by:VGR
ID: 8251824
please not that the bljak script :
-builds upon mine
-doesn't test the validity of the date (MySql as a perpetual calendar, very handy for this kind of stuff)
-uses alphabetical sorting on dates : this culd pose problems depending on the locale setting for date (huh huh huh)
-will accept days and months being 0
-uses an ereg_replace() that you'll never maintain nor understand again in 2 months.

My code is always the best solution possible given some constraints I impose myself (readability, understandable/expandable by other people, etc)

Good luck...
0
 
LVL 4

Expert Comment

by:bljak
ID: 8252014
Dear VGR
as for the points 1 and 2 and 3 and 4 and 5
- noone said that he has mysql or any sql installed, (huh huh)
- it does have validate check, there is even a piece of code commented with //just a reverse check
- it converts all stuf into int
- will accept 0, but in reverse check it will throw an error (see point 2)
- there is no ereg_replace(); (only ereg() to match correct input)

:)))

//bljak
0
 
LVL 15

Expert Comment

by:VGR
ID: 8252033
I don't care. If he's happy with your stuff, then let's rock 'n' roll !  :)))
0

Featured Post

Secure Your WordPress Site: 5 Essential Approaches

WordPress is the web's most popular CMS, but its dominance also makes it a target for attackers. Our eBook will show you how to:

Prevent costly exploits of core and plugin vulnerabilities
Repel automated attacks
Lock down your dashboard, secure your code, and protect your users

Question has a verified solution.

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

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
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 …
Suggested Courses

777 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