Browse Source

Allow empty date fields.

Make allowEmpty() work with date/datetime/time fields. This lets baked
validators work well with optional/nullable date columns.

Refs #5611
Mark Story 11 years ago
parent
commit
05372b5242
2 changed files with 50 additions and 0 deletions
  1. 4 0
      src/Validation/Validator.php
  2. 46 0
      tests/TestCase/Validation/ValidatorTest.php

+ 4 - 0
src/Validation/Validator.php

@@ -525,6 +525,10 @@ class Validator implements \ArrayAccess, \IteratorAggregate, \Countable
         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;
     }
 

+ 46 - 0
tests/TestCase/Validation/ValidatorTest.php

@@ -196,6 +196,52 @@ class ValidatorTest extends TestCase
     }
 
     /**
+     * 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.
      *
      * @return void