Date validate

PHP July 13th, 2007

My friend Shaun asked me if PHP can do a date validation and I was sure it could with all the built-in date function. So no reason to write a custom date validation function from scratch.

A quick google search and check on php.net shows that you can use PHP’s checkdate function to do the validation.

Here’s an example:-


Here’s the full source code:


<form method=post action=<? $_SERVER[’PHP_SELF’] ?>>
    Enter date<input type=text value=” name=dt>
    <input type=submit>
</form>
<?

  if (isset($_POST[’dt’])) {
      if ($_POST[’dt’]==”) {
           echo  “Please enter a date”;
           die();
      }
      validate();
  }

  function validate() {
        $dt=$_POST[’dt’];
        //$dt=”02/28/2007″;
        $arr=split(”/”,$dt); // splitting the array
        $mm=$arr[1]; // first element of the array is month
        $dd=$arr[0]; // second element is date
        $yy=$arr[2]; // third element is year
        If(!checkdate($mm,$dd,$yy)){
        echo “invalid date”;
        } else {
        echo “Entry date is correct”;
      }
  }
?>




Leave a Comment