Validating dates with PHP

15 October 2008 by Gavin Holt, No Comments

Since I have got into building dynamic websites, I have often found myself building forms to gather dates and times of events, birthdays, booking requests. In fact, when building large applications, it is almost guaranteed you will need to take some form of date from a user. But, when building websites, we can never trust our users input, it is essential to the integrity of the system that all data is correct. This means we must check all data coming in and reject anything which may cause problems.

Dates can be a very complex thing to validate, Days in a month and leap years both present problems.

PHP comes with a very clever built in function called checkdate. Many developers have 3 separate inputs or drop downs to stop users from entering false dates. When I am filling in forms, I find this irritating and time consuming.

It doesn’t have to be harder to validate a date from a single text box.

<?php
function realDate($dateString){ // Define Function
	$parts = explode("/",$dateString); //Split the date into its seperate part Day, Month and year and store them in an array
	if(count($parts) == 3){ // Check that the user supplied the date with all three bits of information, if it doesn't we return false straight away
		$day = $parts[0]; //As I am expecting my users to enter the date in a Day/Month.Year format, the day is the first in the array
		$month = $parts[1]; // Month is second
		$year = $parts[2]; // Year is last
		/*
		 Use PHP's built in date check function, passing in our variables in the right order.
		 If it is right, the function will return true and in turn, our function will return true
		*/
		if(checkdate($month,$day,$year)==true){
			return true;
		}else{ // checkdate returns false, so do we
			return false;
		}
	}else{// User didn't supply all three peices of information, Return False
		return false; 
	}
}//End Function
?>

Run a date in the format day/month/year (01/01/1970 for example) and it will return true if this is a real date and false if it isn’.

I have provided a fully commented source file and example to help you see this is action.

Live Example

Source Code

Big thanks to Rich Willars for his advice on cleaning the user input.

As always, if you see any way of improving the script, or a flaw in mine please comment.

Leave a Reply