diff --git a/readme.md b/readme.md index d9db891..a236bc5 100644 --- a/readme.md +++ b/readme.md @@ -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()); +``` \ No newline at end of file diff --git a/spec/Laracasts/Validation/FormValidatorContextSpec.php b/spec/Laracasts/Validation/FormValidatorContextSpec.php new file mode 100644 index 0000000..9ed2354 --- /dev/null +++ b/spec/Laracasts/Validation/FormValidatorContextSpec.php @@ -0,0 +1,38 @@ +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'] + ]; +} diff --git a/src/Laracasts/Validation/FormValidator.php b/src/Laracasts/Validation/FormValidator.php index ec4fd62..9109547 100644 --- a/src/Laracasts/Validation/FormValidator.php +++ b/src/Laracasts/Validation/FormValidator.php @@ -5,6 +5,11 @@ abstract class FormValidator { + /** + * @var string + */ + protected $context; + /** * @var ValidatorFactory */ @@ -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 */