Skip to content

Commit

Permalink
Allow empty date fields.
Browse files Browse the repository at this point in the history
Make allowEmpty() work with date/datetime/time fields. This lets baked
validators work well with optional/nullable date columns.

Refs #5611
  • Loading branch information
markstory committed Feb 1, 2015
1 parent efdcef5 commit 05372b5
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Validation/Validator.php
Expand Up @@ -525,6 +525,10 @@ protected function _fieldIsEmpty($data)
if (empty($data) && $data !== '0' && $data !== false && $data !== 0 && $data !== 0.0) {
return true;
}
if (is_array($data) && (isset($data['year']) || isset($data['hour']))) {
$value = implode('', $data);
return strlen($value) === 0;
}
return false;
}

Expand Down
46 changes: 46 additions & 0 deletions tests/TestCase/Validation/ValidatorTest.php
Expand Up @@ -195,6 +195,52 @@ public function testAllowEmpty()
$this->assertEquals('update', $validator->field('title')->isEmptyAllowed());
}

/**
* Tests the allowEmpty method with date/time fields.
*
* @return void
*/
public function testAllowEmptyDateTime()
{
$validator = new Validator;
$validator->allowEmpty('created')
->add('created', 'date', ['rule' => 'date']);

$data = [
'created' => [
'year' => '',
'month' => '',
'day' => ''
]
];
$result = $validator->errors($data);
$this->assertEmpty($result, 'No errors on empty date');

$data = [
'created' => [
'year' => '',
'month' => '',
'day' => '',
'hour' => '',
'minute' => '',
'second' => '',
'meridian' => '',
]
];
$result = $validator->errors($data);
$this->assertEmpty($result, 'No errors on empty datetime');

$data = [
'created' => [
'hour' => '',
'minute' => '',
'meridian' => '',
]
];
$result = $validator->errors($data);
$this->assertEmpty($result, 'No errors on empty time');
}

/**
* Test the notEmpty() method.
*
Expand Down

0 comments on commit 05372b5

Please sign in to comment.