CDateValidator doesn't validate an "empty" MySQL date string of '0000-00-00'

I’m new at this and probably doing something wrong, but when you use the CDateValidator class, it won’t validate an “empty” MySQL date value of ‘0000-00-00’. I want to do this because I have an optional date field (birthday.)

I’ve figured out how to blank out the default date value, so that nothing shows in the view or update form, and if you don’t enter a date, it will save as ‘0000-00-00’. (I had to substitute an empty validator function to get by the validation step to actually enter a blank field. But now of course illegal data will crash the program, so I realize I need some sort of validation.)

Should I write my own custom date validator, or is there a way to feed the standard CDateValidator class to do what I want?

Here is the code from the Profile.php model of the User Module:

} elseif ($field->field_type=='DATE') {

  $field_rule = array($field->varname, 'type', 'type' => 'date', 'dateFormat' => 'yyyy-mm-dd', 'allowEmpty'=>true);

  if ($field->error_message) $field_rule['message'] = UserModule::t($field->error_message);



Thanks in advance for any insight.

Well I don’t know if I understood correctly, but when I have an optional date/datetime field, I put the following in the model’s beforeSave function:

class Profile extends CActiveRecord



  protected function beforeSave()



    if($this->birthday == '')

      $this->birthday = null;

    return parent::beforeSave();




On the other hand, this wiki gives good explanation of the validation rules, and notably this:

PS: with the first snippet, if someone displays and takes input in a different date format, the same snippet can be adapted (thanks to some post on the forum)

if($this->birthday != '') {

  // example for French date format, for datetime and/or other formats, please adapt

  list($d, $m, $y) = explode('/', $this->birthday);

  $this->birthday = date('Y-m-d', mktime(0, 0, 0, $m, $d, $y));

} else

  $this->birthday = null;

Thanks for your response.

Yeah I read all the documentation. I guess my point was that the validator only accepts NULL or ‘’ as “empty,” whereas there is no such thing as a truly empty date–it’s ‘0000-00-00’. I was hung up on getting the validator to accept the default “empty” date string, instead of giving the validator what it wants, then giving MySQL what IT wants afterward.

Your solution, of course, works for my case also.


The branch it little bit old, but maybe it will help anyone.

You can also add ‘0000-00-00’ to the list of valid formats, like:

array('birthday', 'date', 'format' => array('yyyy-MM-dd', '0000-00-00')),

and it would validate ‘0000-00-00’ as a valid date.