Browse Source

Add a basic compareWith validator for comparing two fields.

This kind of validation is useful for doing password comparisons or
confirming a field with another.

Refs #5746
Mark Story 11 years ago
parent
commit
84e89810ad
2 changed files with 42 additions and 0 deletions
  1. 17 0
      src/Validation/Validation.php
  2. 25 0
      tests/TestCase/Validation/ValidationTest.php

+ 17 - 0
src/Validation/Validation.php

@@ -260,6 +260,23 @@ class Validation
     }
 
     /**
+     * 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.
      *
      * @param string|array $check When used as a string, $regex must also be a valid regular expression.

+ 25 - 0
tests/TestCase/Validation/ValidationTest.php

@@ -2511,4 +2511,29 @@ class ValidationTest extends TestCase
         $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));
+    }
 }