From 81978ef8c7c61bf2c72f5d4513d680eb8d826d69 Mon Sep 17 00:00:00 2001 From: Tom Graham Date: Wed, 19 Jun 2013 21:27:56 +0100 Subject: [PATCH] Added support for non-mandatory fields. Fixes issue #13. --- src/Valitron/Validator.php | 18 ++++++++++++++++++ tests/Valitron/Validate.php | 14 ++++++++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/Valitron/Validator.php b/src/Valitron/Validator.php index 42cdc01..6daf22a 100644 --- a/src/Valitron/Validator.php +++ b/src/Valitron/Validator.php @@ -498,6 +498,11 @@ class Validator foreach($v['fields'] as $field) { $value = isset($this->_fields[$field]) ? $this->_fields[$field] : null; + // Don't validate if the field is not required and the value is empty + if ($v['rule'] !== 'required' && !$this->hasRule('required', $field) && $value == '') { + continue; + } + // Callback is user-specified or assumed method on class if(isset(static::$_rules[$v['rule']])) { $callback = static::$_rules[$v['rule']]; @@ -511,9 +516,22 @@ class Validator } } } + return count($this->errors()) === 0; } + /** + * Determine whether a field is being validated by the given rule. + * + * @param string $name The name of the rule + * @param string $field The name of the field + * @return boolean + */ + protected function hasRule($name, $field) + { + return isset($this->_validations[$name]) && in_array($field, $this->_validations[$name]['fields']); + } + /** * Register new validation rule callback */ diff --git a/tests/Valitron/Validate.php b/tests/Valitron/Validate.php index 2f0bda6..d1ba60d 100644 --- a/tests/Valitron/Validate.php +++ b/tests/Valitron/Validate.php @@ -63,7 +63,7 @@ class ValidateTest extends \PHPUnit_Framework_TestCase 'email' => array('Email should be a valid email address') ); - $v = new Validator(array()); + $v = new Validator(array('name' => '', 'email' => '$')); $v->rule('required', 'name')->message('{field} is required'); $v->rule('email', 'email')->message('{field} should be a valid email address'); @@ -128,7 +128,7 @@ class ValidateTest extends \PHPUnit_Framework_TestCase public function testDifferentInvalid() { - $v = new Validator(array('test1' => 'test', 'test2' => 'test')); + $v = new Validator(array('foo' => 'baz', 'bar' => 'baz')); $v->rule('different', 'foo', 'bar'); $this->assertFalse($v->validate()); } @@ -385,6 +385,16 @@ class ValidateTest extends \PHPUnit_Framework_TestCase $this->assertFalse($v->validate()); } + /** + * @group issue-13 + */ + public function testDateValidWhenEmptyButNotRequired() + { + $v = new Validator(array('date' => '')); + $v->rule('date', 'date'); + $this->assertTrue($v->validate()); + } + public function testDateFormatValid() { $v = new Validator(array('date' => '2013-01-27'));