Skip to content

Commit

Permalink
Add a basic compareWith validator for comparing two fields.
Browse files Browse the repository at this point in the history
This kind of validation is useful for doing password comparisons or
confirming a field with another.

Refs #5746
  • Loading branch information
markstory committed Feb 1, 2015
1 parent ed6d692 commit 84e8981
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/Validation/Validation.php
Expand Up @@ -259,6 +259,23 @@ public static function comparison($check1, $operator = null, $check2 = null)
return false;
}

/**
* Compare one field to another.
*
* If both fields have exactly the same value this method will return true.
*
* @param mixed $check The value to find in $field.
* @param string $field The field to check $check against. This field must be present in $context.
* @param array $context The validation context.
* @return bool
*/
public static function compareWith($check, $field, $context) {
if (!isset($context['data'][$field])) {
return false;
}
return $context['data'][$field] === $check;
}

/**
* Used when a custom regular expression is needed.
*
Expand Down
25 changes: 25 additions & 0 deletions tests/TestCase/Validation/ValidationTest.php
Expand Up @@ -2511,4 +2511,29 @@ public function testUploadedFileWithDifferentFileParametersOrder()
$options = [];
$this->assertTrue(Validation::uploadedFile($file, $options), 'Wrong order');
}

/**
* Test the compareWith method.
*
* @return void
*/
public function testCompareWith()
{
$context = [
'data' => [
'other' => 'a value'
]
];
$this->assertTrue(Validation::compareWith('a value', 'other', $context));

$context = [
'data' => [
'other' => 'different'
]
];
$this->assertFalse(Validation::compareWith('a value', 'other', $context));

$context = [];
$this->assertFalse(Validation::compareWith('a value', 'other', $context));
}
}

0 comments on commit 84e8981

Please sign in to comment.