Browse Source

Adding a custom error message to Validator::allowEmpty()

See #8797
Florian Krämer 10 years ago
parent
commit
fe4f1f45b7
2 changed files with 20 additions and 2 deletions
  1. 5 1
      src/Validation/Validator.php
  2. 15 1
      tests/TestCase/Validation/ValidatorTest.php

+ 5 - 1
src/Validation/Validator.php

@@ -474,11 +474,15 @@ class Validator implements ArrayAccess, IteratorAggregate, Countable
      * @param bool|string|callable $when Indicates when the field is allowed to be empty
      * Valid values are true (always), 'create', 'update'. If a callable is passed then
      * the field will allowed to be empty only when the callback returns true.
+     * @param string|null $message The message to show if the field is not
      * @return $this
      */
-    public function allowEmpty($field, $when = true)
+    public function allowEmpty($field, $when = true, $message = null)
     {
         $this->field($field)->isEmptyAllowed($when);
+        if ($message) {
+            $this->_allowEmptyMessages[$field] = $message;
+        }
         return $this;
     }
 

+ 15 - 1
tests/TestCase/Validation/ValidatorTest.php

@@ -644,7 +644,21 @@ class ValidatorTest extends TestCase
     }
 
     /**
-     * Tests custom error mesages generated when a field is not allowed to be empty
+     * Tests custom error messages generated when a field is allowed to be empty
+     *
+     * @return void
+     */
+    public function testCustomErrorsWithAllowedEmpty()
+    {
+        $validator = new Validator;
+        $validator->allowEmpty('title', false, 'Custom message');
+        $errors = $validator->errors(['title' => null]);
+        $expected = ['title' => ['_empty' => 'Custom message']];
+        $this->assertEquals($expected, $errors);
+    }
+
+    /**
+     * Tests custom error messages generated when a field is not allowed to be empty
      *
      * @return void
      */