Date Validation in PHP
In this Tutorial you'll learn about Validating Date fields using PHP code in 'dd/mm/yyyy' Format. It is in general a good practice to validate the date value when it is obtained using forms through user input. PHP can be used to validate date values as explained in the following example:
Note: We have also provided the PHP date validation for 'mm/dd/yyyy' Format.
Enter Date *(dd/mm/yyyy)
Output: Error Enter the date in 'dd/mm/yyyy' format
Use the sample code given below in your test page and try it yourself.
Sample PHP Code
<?php
//Check whether the submission is made
if(!isset($_POST["hidSubmit"])){
//Declarate the necessary variables
$strdate="";
$strdate1="";
DisplayForm();
}
else{
$strdate=$_POST["txtdate"];
//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;
?>
HTML code for the form follows..
Cut 'n' paste HTML code for the above example
HTML CODE
Explanation of the Code
Testing is done by PHP code only. This code contains one expression for validating whether the entered text is a valid number or not.
Expression ^[0-9]+$^ :-Indicates the beginning of the string
[0-9]+ :- indicates that the string begins with a number between (0-9) and is followed by numbers.
$ :- Indicates the end of the String