Update checkRequired to simply check if an array key is present rather than isset (which fails if the value is null)

This commit is contained in:
Ryan Morris 2012-11-02 09:35:02 -04:00 committed by Jose Lorenzo Rodriguez
parent 9007406b9d
commit fa759231da
2 changed files with 28 additions and 2 deletions

View file

@ -163,9 +163,9 @@ class CakeValidationRule {
*/
public function checkRequired($field, &$data) {
return (
(!isset($data[$field]) && $this->isRequired() === true) ||
(!array_key_exists($field, $data) && $this->isRequired() === true) ||
(
isset($data[$field]) && (empty($data[$field]) &&
array_key_exists($field, $data) && (empty($data[$field]) &&
!is_numeric($data[$field])) && $this->allowEmpty === false
)
);

View file

@ -171,4 +171,30 @@ class CakeValidationRuleTest extends CakeTestCase {
$Rule->isUpdate(true);
$this->assertTrue($Rule->isEmptyAllowed());
}
/**
* Test checkRequired method
*
* @return void
*/
public function testCheckRequiredWhenRequiredAndAllowEmpty() {
$Rule = $this->getMock('CakeValidationRule', array('isRequired'));
$Rule->expects($this->any())
->method('isRequired')
->will($this->returnValue(true));
$Rule->allowEmpty = true;
$fieldname = 'field';
$data = array(
$fieldname => null
);
$this->assertFalse($Rule->checkRequired($fieldname, $data), "A null but present field should not fail requirement check if allowEmpty is true");
$Rule->allowEmpty = false;
$this->assertTrue($Rule->checkRequired($fieldname, $data), "A null but present field should fail requirement check if allowEmpty is false");
}
}