Software and Other Mysteries

On code and productivity with a dash of unicorn dust.

Simple date validation

posted in PHP CodeIgniter

Date validation usually means regular expressions, and regular expressions usually means headache. All in all, I do think that PHP’s date handling is pretty sweet, but native validation is still lacking. With PHP 5.3 though, we are one step closer thanks to a new function with the infinitely long name date_parse_from_format. I’m going to show you how it can be used to create a validation function for any PHP date format.

So, the date_parse_from_format takes a date format and a string and parses the date to an associative array. Along with this I used the native checkdate which takes the argument month, day and year and tells you whether or not it is a valid date.

<?php
class MY_Form_Validation extends CI_Form_Validation {

	function __construct()
	{
		parent::__construct();
	}

	/**
	 * Validate date according to the specified format.
	 *
	 * @access	public
	 * @param	string
     * @param	date format
	 * @return	bool
	 */
	function valid_date($str, $format)
	{
        $date = date_parse_from_format($format, $str);
        return checkdate($date['month'], $date['day'], $date['year']);
	}

}

The valid_date function can be used by anyone sporting a PHP 5.3 install on their web host. Since I’m using CodeIgniter I simply put this function in MY_Form_Validation, which means I can easily use this function like any standard CI validation function, i.e.


$this->form_validation->set_rules('birth', 'Birthday', 'valid_date[d-m-Y]');

This is a really handy trick for those otherwise (for me, at least) nasty date validations.

Comments