Date Validation with CI

The new release of CodeIgniter (1.6.2) still doesn’t have a date validation function included in the validation class. However, no need to worry. I will show you in a couple easy steps how to add this in.

First off let’s start by saying that we will validate dates in the MM/DD/YYYY format. If you need to change this it only takes a couple of simple edits to the regular expression.

The files that need to be edited are the validation.php (located @ CI → System → Libraries) and the English Language Validation file, validation_lang.php (located @ CI → System → Language → English).

Here is the code to check to make sure the date is in the right format and contains numerics.

/**
* Valid Date
*
* @access    public
* @param    string
* @return    bool
*/
function valid_date($str) {
if(!preg_match("/[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}/",$str)){
return FALSE;
}
else {
/* 1. Extract the numeric data presented as MM/DD/YYYY */
list($MM, $DD, $YYYY) = explode("/",$str);
/* 2. Validate the date */
if(!checkdate($MM, $DD, $YYYY)) {
return FALSE;
}
}
}

// --------------------------------------------------------------------

You can add this code to the end of the validation.php file.

Now in your controller when you are validating data you just have to add valid_date text to the mix. However, you still need to add an error message into the validation dictionary. You can add anything you want but open up the validation_lang.php and append the following line of code.

$lang['valid_date'] = "The %s field must contain a vaild Date in the mm/dd/yyyy format.";

You can get more information on the CI validation class here .

That’s it..happy validating!