Randy L
Randy L

Reputation: 14736

Date validation in Cake

How can I get the built-in date formatting working in my Cake app? Maybe I am making some simple mistake. I'm focused on the model code right now, I think this is what I am screwing up.

On the page it looks like it's working, showing three select widgets with months, days, years in that order. However, when I submit the form I'm getting the "Must be a valid date" message.

Here's the view code I have:

echo $this->Form->create('Subscription');
echo $this->Form->input('starts',array('type'=>'date','dateFormat'=>'MDY'));
echo $this->Form->end('Submit', true);

And in my model the validation looks like this:

'starts' => array(
    'date' => array(
    'rule' => array('date', array('MDY')),
    'message' => 'Must be a valid date',
    ),
    'notempty' => array(
        'rule' => array('notempty'),
        'message' => 'Start date is required',
    ),
),

The field I'm trying to update is declared as DATETIME in the mysql db, in case that makes a difference.

Upvotes: 1

Views: 3004

Answers (3)

bigmike7801
bigmike7801

Reputation: 3970

I found the following information in the Cake 2.0 data validation documentation (http://book.cakephp.org/2.0/en/models/data-validation.html#Validation::datetime):

Validation::datetime(array $check, mixed $dateFormat = 'ymd', string $regex = null)
This rule ensures that the data is a valid datetime format. A parameter (which can be an array) can be passed to specify the format of the date. The value of the parameter can be one or more of the following:

'dmy' e.g. 27-12-2006 or 27-12-06 (separators can be a space, period, dash, forward slash)
'mdy' e.g. 12-27-2006 or 12-27-06 (separators can be a space, period, dash, forward slash)
'ymd' e.g. 2006-12-27 or 06-12-27 (separators can be a space, period, dash, forward slash)
'dMy' e.g. 27 December 2006 or 27 Dec 2006
'Mdy' e.g. December 27, 2006 or Dec 27, 2006 (comma is optional)
'My'  e.g. (December 2006 or Dec 2006)
'my'  e.g. 12/2006 or 12/06 (separators can be a space, period, dash, forward slash)
 if no keys are supplied, the default key that will be used is 'ymd':

Upvotes: 1

Leo
Leo

Reputation: 6571

I don't remember off the top of my head, but I think you have to use the generated date inputs to construct your own date.

!!- Scrub that -!!

‘Mdy’ e.g. December 27, 2006 or Dec 27, 2006 (comma is optional)

If no keys are supplied, the default key that will be used is ‘ymd’.

I'm with SpawnCxy on this.

Upvotes: 1

Young
Young

Reputation: 8356

I don't find the parameter MDY in the parameter list.You can try Mdy.

Upvotes: 0

Related Questions