Skip to content

Commit

Permalink
adds validation for arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
thinkingmedia committed Jun 30, 2016
1 parent fd66542 commit 40499d4
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/Validation/Validation.php
Expand Up @@ -1181,6 +1181,17 @@ public static function isInteger($value)
return (bool)preg_match('/^-?[0-9]+$/', $value);
}

/**
* Check that the input value is an array.
*
* @param array $value
* @return bool
*/
public static function isArray($value)
{
return is_array($value);
}

/**
* Converts an array representing a date or datetime into a ISO string.
* The arrays are typically sent for validation from a form generated by
Expand Down
17 changes: 17 additions & 0 deletions src/Validation/Validator.php
Expand Up @@ -1301,6 +1301,23 @@ public function integer($field, $message = null, $when = null)
]);
}

/**
* Add a validation rule to ensure that a field contains an array.
*
* @param string $field The field you want to apply the rule to.
* @param string|null $message The error message when the rule fails.
* @param string|callable|null $when Either 'create' or 'update' or a callable that returns
* true when the validation rule should be applied.
* @return $this
*/
public function isArray($field, $message = null, $when = null)
{
$extra = array_filter(['on' => $when, 'message' => $message]);
return $this->add($field, 'isArray', $extra + [
'rule' => 'isArray'
]);
}

/**
* Add a validation rule for a multiple select. Comparison is case sensitive by default.
*
Expand Down
17 changes: 17 additions & 0 deletions tests/TestCase/Validation/ValidationTest.php
Expand Up @@ -14,11 +14,13 @@
*/
namespace Cake\Test\TestCase\Validation;

use Cake\Collection\Collection;
use Cake\Core\Configure;
use Cake\Filesystem\File;
use Cake\I18n\I18n;
use Cake\TestSuite\TestCase;
use Cake\Validation\Validation;
use Cake\Validation\Validator;
use Locale;

require_once __DIR__ . '/stubs.php';
Expand Down Expand Up @@ -2667,6 +2669,21 @@ public function testLongitude()
$this->assertFalse(Validation::longitude('-190.52236'));
}

/**
* Test isArray
*
* @return void
*/
public function testIsArray()
{
$this->assertTrue(Validation::isArray([]));
$this->assertTrue(Validation::isArray([1,2,3]));
$this->assertTrue(Validation::isArray(['key'=>'value']));
$this->assertFalse(Validation::isArray('[1,2,3]'));
$this->assertFalse(Validation::isArray(new Collection([])));
$this->assertFalse(Validation::isArray(10));
}

/**
* Test isInteger
*
Expand Down

0 comments on commit 40499d4

Please sign in to comment.