Skip to content

Commit

Permalink
Merge pull request #171 from vlucas/withDataBugfix
Browse files Browse the repository at this point in the history
With data bugfix
  • Loading branch information
willemwollebrants authored Dec 9, 2016
2 parents 399004d + 768a26c commit d9b1548
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/Valitron/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -1204,8 +1204,8 @@ public function rules($rules)
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;
}
}
8 changes: 7 additions & 1 deletion tests/Valitron/ValidateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1164,10 +1164,16 @@ public function testWithData()
//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());
}
}

Expand Down

0 comments on commit d9b1548

Please sign in to comment.