Luke Stokes Mon Mar 05 18:22:45 -0500 2012

Subject: How to validate a date field?

I'd like to throw a validation error if someone tries to enter a date that isn't in the YYYY-MM-DD format. I've added this validation:

    static $validates_format_of = array(
            array('start_date', 'with' => '/^(19|20)\d\d[-](0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])$/', 'message' => 'is invalid. It must be a date in the YYYY-MM-DD format.', 'allow_null' => true), // need to improve this to validate the date itself
            array('end_date', 'with' => '/^(19|20)\d\d[-](0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])$/', 'message' => 'is invalid. It must be a date in the YYYY-MM-DD format.', 'allow_null' => true) // need to improve this to validate the date itself
    );

But it does not seem to be working... stranger still, if I pass in a valid date, it errors. If I pass in just a string value, it works.

When I look at line 430 or so of Validation where this is: if (!@preg_match($expression, $var)) { and dump those out, I see that @var has all kinds of stuff in it and it fails. Is that due to the if ($value instanceof DateTime) check in Model.php?

I'm confused. Without validation rules, it appears that any invalid date value is just ignored completely, but I'd like to throw an error instead.