From 0d77529c90c13d74870ff379dfa5a163abcb0d88 Mon Sep 17 00:00:00 2001 From: Tilen Majerle Date: Mon, 30 Nov 2015 22:23:21 +0100 Subject: [PATCH 1/2] Added "optional" rule validation With 'optional' rule validation, values does not need to be included in data array. However, if they are, they must pass validation. Before this patch, if you pass data with empty ( '' ) value, then it is ignored if "required" was not added. With this version, this is now fixed. Text case available here: http://pastebin.com/N2eQjJys --- src/Valitron/Validator.php | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/Valitron/Validator.php b/src/Valitron/Validator.php index 7322357..d77ab39 100644 --- a/src/Valitron/Validator.php +++ b/src/Valitron/Validator.php @@ -731,6 +731,12 @@ class Validator return $isInstanceOf; } + //Validate optional field + protected function validateOptional($field, $value, $params) { + //Always return true + return true; + } + /** * Get array of fields and data * @@ -868,7 +874,9 @@ class Validator list($values, $multiple) = $this->getPart($this->_fields, explode('.', $field)); // Don't validate if the field is not required and the value is empty - if ($v['rule'] !== 'required' && !$this->hasRule('required', $field) && (! isset($values) || $values === '' || ($multiple && count($values) == 0))) { + if ($this->hasRule('optional', $field) && isset($values)) { + //Continue with execution below if statement + } elseif ($v['rule'] !== 'required' && !$this->hasRule('required', $field) && (! isset($values) || $values === '' || ($multiple && count($values) == 0))) { continue; } From 9afa605dc3564d1fc580c1f67565ca6b9146c907 Mon Sep 17 00:00:00 2001 From: Willem Wollebrants Date: Mon, 22 Feb 2016 12:13:02 +0100 Subject: [PATCH 2/2] Add tests for 'optional' rule --- tests/Valitron/ValidateTest.php | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/Valitron/ValidateTest.php b/tests/Valitron/ValidateTest.php index 9834d2e..996c4a2 100644 --- a/tests/Valitron/ValidateTest.php +++ b/tests/Valitron/ValidateTest.php @@ -1085,6 +1085,27 @@ class ValidateTest extends BaseTestCase ), ); } + + public function testOptionalProvidedValid() + { + $v = new Validator(array('address' => 'user@example.com')); + $v->rule('optional', 'address')->rule('email', 'address'); + $this->assertTrue($v->validate()); + } + + public function testOptionalProvidedInvalid() + { + $v = new Validator(array('address' => 'userexample.com')); + $v->rule('optional', 'address')->rule('email', 'address'); + $this->assertFalse($v->validate()); + } + + public function testOptionalNotProvided() + { + $v = new Validator(array()); + $v->rule('optional', 'address')->rule('email', 'address'); + $this->assertTrue($v->validate()); + } } function sampleFunctionCallback($field, $value, array $params) {