Matthew Machuga Thu Jan 06 12:12:18 -0500 2011

Subject: Date validates_format_of issue

I've tried on both the stable and nightly build, but I can't seem to correctly utilize validates_by_format on a date field. Is there a certain way I need to reference this since any date is a datetime object?

My validator is:

static $validates_format_of = array(
        array('my_date', 'with' => '/[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}/')

Any recommendations or info?

Jacques Fuentes Thu Jan 06 21:30:59 -0500 2011

Well, since it's a DateTime object, you can format it however you want. Also, PHP-AR automatically formats the date as you'd like when inserting into the database by using the specified default date format found here:$DEFAULT_FORMAT

Matthew Machuga Fri Jan 07 16:09:14 -0500 2011


Right; I think I poorly explained that. I'd like to validate that it matches that format prior to being made into a DateTime object so it doesn't try to transform text into a DateTime object, causing an exception. It looks like it may not be possible as it stands?

Benjamin P Sun Jan 09 14:47:31 -0500 2011

Well, you could just convert it into a DateTime object and see if it was succesful? Anyway, if the kind of validation you like is not built-in, you can always use a custom function validate():

Jacques Fuentes Sun Jan 09 15:14:35 -0500 2011

You should be able to use a custom setter to avoid exceptions being thrown when the text is not in a valid format:

class MyClass
  public function set_my_date($value)
    # if bad format then catch exception
    $this->assign_attribute('my_date', $value);
Matthew Machuga Mon Jan 10 11:26:18 -0500 2011

Benjamin: I use the custom validator currently and it suffices for sure; I was on the stable release before so I didn't have it available initially. Thanks for chiming in :)

Jacques: Not a bad idea to intercept it in that manner either.

I just try to keep it consistent when handling validation and wasn't positive if I could intercept and validate the string using standard methods before it was transformed into a DateTime object using $validates_format_of .

Thanks for the suggestions.