From f8290a8c59e1cf2bf7dfb656a8b722bc494286eb Mon Sep 17 00:00:00 2001 From: Willem Wollebrants Date: Fri, 9 Dec 2016 11:44:39 +0100 Subject: [PATCH 1/2] Fix bug where Validator::withData would also erase all rules --- src/Valitron/Validator.php | 2 +- tests/Valitron/ValidateTest.php | 8 +++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/Valitron/Validator.php b/src/Valitron/Validator.php index c5947ae..965c0f8 100644 --- a/src/Valitron/Validator.php +++ b/src/Valitron/Validator.php @@ -1204,8 +1204,8 @@ class Validator public function withData($data, $fields = array()) { $clone = clone $this; - $clone->reset(); $clone->_fields = !empty($fields) ? array_intersect_key($data, array_flip($fields)) : $data; + $clone->_errors = array(); return $clone; } } diff --git a/tests/Valitron/ValidateTest.php b/tests/Valitron/ValidateTest.php index ceb10bb..4a91b33 100644 --- a/tests/Valitron/ValidateTest.php +++ b/tests/Valitron/ValidateTest.php @@ -1164,10 +1164,16 @@ class ValidateTest extends BaseTestCase //validation failed, so must have errors $this->assertFalse($v->validate()); $this->assertNotEmpty($v->errors()); - //create copy with different data + + //create copy with valid data $v2 = $v->withData(array('name' => 'Chester Tester')); $this->assertTrue($v2->validate()); $this->assertEmpty($v2->errors()); + + //create copy with invalid data + $v3 = $v->withData(array('firstname' => 'Chester')); + $this->assertFalse($v3->validate()); + $this->assertNotEmpty($v3->errors()); } } From 768a26c7f4ad1bd1ae913020dd22c3684fc60f93 Mon Sep 17 00:00:00 2001 From: Willem Wollebrants Date: Fri, 9 Dec 2016 11:50:13 +0100 Subject: [PATCH 2/2] Add note about re-usability to readme --- README.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/README.md b/README.md index 18ee53c..bf18d32 100644 --- a/README.md +++ b/README.md @@ -307,6 +307,19 @@ $v->validate(); This introduces a new set of tags to your error language file which looks like `{field}`, if you are using a rule like `equals` you can access the second value in the language file by incrementing the field with a value like `{field1}`. +## Re-use of validation rules + +You can re-use your validation rules to quickly validate different data with the same rules by using the withData method: + +```php +$v = new Valitron\Validator(array()); +$v->rule('required', 'name')->message('{field} is required'); +$v->validate(); //false + +$v2 = $v->withData(array('name'=>'example')); +$v2->validate(); //true +``` + ## Running Tests The test suite depends on the Composer autoloader to load and run the