Browse Source

merged branch marcw/validator-choice (PR #1577)

Commits
-------

df57e0f [Validator] Added strict option to ChoiceConstraint.

Discussion
----------

[Validator] Added strict option to ChoiceConstraint.

By default, ChoiceValidator was ensuring strict type when checking if value is present in choices. This behavior is a problem when you want to validate against integer values. As all data you will receive from a request will be typed as a string, you won't be able to validate these numeric values.
This patch solves this.

In order for being nice to developers, I've set "strict" to false by default.
Fabien Potencier 14 years ago
parent
commit
4a7b7597d8

+ 1 - 0
src/Symfony/Component/Validator/Constraints/Choice.php

@@ -19,6 +19,7 @@ class Choice extends Constraint
     public $choices;
     public $callback;
     public $multiple = false;
+    public $strict = false;
     public $min = null;
     public $max = null;
     public $message = 'The value you selected is not a valid choice';

+ 1 - 1
src/Symfony/Component/Validator/Constraints/ChoiceValidator.php

@@ -73,7 +73,7 @@ class ChoiceValidator extends ConstraintValidator
 
                 return false;
             }
-        } elseif (!in_array($value, $choices, true)) {
+        } elseif (!in_array($value, $choices, $constraint->strict)) {
             $this->setMessage($constraint->message, array('{{ value }}' => $value));
 
             return false;

+ 11 - 0
tests/Symfony/Tests/Component/Validator/Constraints/ChoiceValidatorTest.php

@@ -182,4 +182,15 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
             '{{ limit }}' => 2,
         ));
     }
+
+    public function testStrictIsFalse()
+    {
+        $constraint = new Choice(array(
+            'choices' => array(1, 2),
+            'strict' => false,
+        ));
+
+        $this->assertTrue($this->validator->isValid('2', $constraint));
+        $this->assertTrue($this->validator->isValid(2, $constraint));
+    }
 }