Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,30 @@ Now, just inject this object into your controller or application service, and ca
```php
$this->registrationForm->validate(Input::all());
```

## Optional

You can also create a set of nested rules like this:

```php
/**
* Validation rules for registering
*
* @var array
*/
protected $rules = [
'store' => [
'username' => 'required',
'email' => 'required|unique:users',
],
'update' => [
'username' => 'required',
]
];
```

To call the set of rules you want to use, simply set a context on the validator before calling `validate()`

```php
$this->registrationForm->setContext('store')->validate(Input::all());
```
38 changes: 38 additions & 0 deletions spec/Laracasts/Validation/FormValidatorContextSpec.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

namespace spec\Laracasts\Validation;

use Laracasts\Validation\FactoryInterface;
use Laracasts\Validation\ValidatorInterface;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class FormValidatorContextSpec extends ObjectBehavior
{
function let(FactoryInterface $validatorFactory)
{
$this->beAnInstanceOf('spec\Laracasts\Validation\AnotherExampleValidator');
$this->beConstructedWith($validatorFactory);
}

function it_allows_setting_of_a_context()
{
$this->setContext('store');

$this->getContext()->shouldReturn('store');
}

function it_returns_correct_validation_rules()
{
$this->setContext('store');

$this->getValidationRules()->shouldReturn(array('username' => 'required'));
}

}

class AnotherExampleValidator extends \Laracasts\Validation\FormValidator {
protected $rules = [
'store' => ['username' => 'required']
];
}
24 changes: 24 additions & 0 deletions src/Laracasts/Validation/FormValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@

abstract class FormValidator {

/**
* @var string
*/
protected $context;

/**
* @var ValidatorFactory
*/
Expand Down Expand Up @@ -58,9 +63,28 @@ public function validate($formData)
*/
public function getValidationRules()
{
if( ! is_null($this->context) && array_key_exists($this->context, $this->rules)) return $this->rules[$this->context];

return $this->rules;
}

/**
* @return FormValidator
*/
public function setContext($context)
{
$this->context = $context;
return $this;
}

/**
* @return string
*/
public function getContext()
{
return $this->context;
}

/**
* @return mixed
*/
Expand Down