Posted by: prajapatinilesh | September 19, 2007

Date Validation in PHP

<?
//Example 1
//if date is in mm/dd/yyyy
//$dateVal = ’13/20/2007 04:06 PM’;
$dateVal = ’12/20/2007 04:06 PM’;
$dateArray = explode(‘/’,$dateVal);
echo “<pre>”;
print_r($dateArray);
echo “</pre>”;
$month = trim($dateArray[0]);
$day = trim($dateArray[1]);
$year = trim($dateArray[2]);
$year = substr($year,0,4);
echo $month. ‘/’ .$day. ‘/’ . $year;
echo “<br>”;
//Validate a Gregorian date (PHP 3, PHP 4, PHP 5)
//bool checkdate ( int month, int day, int year )
var_dump(checkdate($month, $day, $year));
?>
//*********************************************************
<?php
//Example 2 //Reference site Name: http://smartwebby.com/PHP/datevalidation.asp
$strdate=$_POST[“txtdate”];  //$strdate=’01/01/2007′;
//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”;}
}
}
}
?>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: