From 6881bdaf027fdfd8b90db4fe1bd61c1c606c43f0 Mon Sep 17 00:00:00 2001 From: Jason Walton Date: Mon, 11 Jun 2012 09:18:42 -0700 Subject: [PATCH] Added required_with validation rule to conditionally require an attribute based on the presence of another attribute Signed-off-by: Jason Walton --- laravel/documentation/validation.md | 3 +++ laravel/validator.php | 23 ++++++++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/laravel/documentation/validation.md b/laravel/documentation/validation.md index 49401439..528cea75 100644 --- a/laravel/documentation/validation.md +++ b/laravel/documentation/validation.md @@ -63,6 +63,9 @@ #### Validate that an attribute is present and is not an empty string: 'name' => 'required' +#### Validate that an attribute is present, when another attribute is present: + 'last_name' => 'required_with:first_name' + ### Alpha, Alpha Numeric, & Alpha Dash diff --git a/laravel/validator.php b/laravel/validator.php index 3290bc17..968e94b7 100644 --- a/laravel/validator.php +++ b/laravel/validator.php @@ -214,7 +214,7 @@ protected function validatable($rule, $attribute, $value) */ protected function implicit($rule) { - return $rule == 'required' or $rule == 'accepted'; + return $rule == 'required' or $rule == 'accepted' or $rule == 'required_with'; } /** @@ -257,6 +257,27 @@ protected function validate_required($attribute, $value) return true; } + /** + * Validate that an attribute exists in the attributes array, if another + * attribute exists in the attributes array. + * + * @param string $attribute + * @param mixed $value + * @param array $parameters + * @return bool + */ + protected function validate_required_with($attribute, $value, $parameters) + { + $other = $parameters[0]; + + if ($this->validate_required($other, $this->attributes[$other])) + { + return $this->validate_required($attribute, $value); + } + + return true; + } + /** * Validate that an attribute has a matching confirmation attribute. *