Skip to content

Commit

Permalink
Add exclude validation rule (laravel#38537)
Browse files Browse the repository at this point in the history
  • Loading branch information
bastien-phi authored and victorvilella committed Oct 12, 2021
1 parent 6dedaa9 commit e64ee03
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
10 changes: 10 additions & 0 deletions src/Illuminate/Validation/Concerns/ValidatesAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -1534,6 +1534,16 @@ public function validateProhibitedUnless($attribute, $value, $parameters)
return true;
}

/**
* Indicate that an attribute is excluded.
*
* @return bool
*/
public function validateExclude()
{
return false;
}

/**
* Indicate that an attribute should be excluded when another attribute has a given value.
*
Expand Down
2 changes: 1 addition & 1 deletion src/Illuminate/Validation/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ class Validator implements ValidatorContract
*
* @var string[]
*/
protected $excludeRules = ['ExcludeIf', 'ExcludeUnless', 'ExcludeWithout'];
protected $excludeRules = ['Exclude', 'ExcludeIf', 'ExcludeUnless', 'ExcludeWithout'];

/**
* The size related validation rules.
Expand Down
43 changes: 43 additions & 0 deletions tests/Validation/ValidationValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6243,6 +6243,49 @@ public function testExcludeIfWhenValidationFails($rules, $data, $expectedMessage
$this->assertSame($expectedMessages, $validator->messages()->toArray());
}

public function providesPassingExcludeData()
{
return [
[
[
'has_appointment' => ['required', 'bool'],
'appointment_date' => ['exclude'],
], [
'has_appointment' => false,
'appointment_date' => 'should be excluded',
], [
'has_appointment' => false,
],
],
];
}

/**
* @dataProvider providesPassingExcludeData
*/
public function testExclude($rules, $data, $expectedValidatedData)
{
$validator = new Validator(
$this->getIlluminateArrayTranslator(),
$data,
$rules
);

$passes = $validator->passes();

if (! $passes) {
$message = sprintf("Validation unexpectedly failed:\nRules: %s\nData: %s\nValidation error: %s",
json_encode($rules, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES),
json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES),
json_encode($validator->messages()->toArray(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)
);
}

$this->assertTrue($passes, $message ?? '');

$this->assertSame($expectedValidatedData, $validator->validated());
}

public function testExcludingArrays()
{
$validator = new Validator(
Expand Down

0 comments on commit e64ee03

Please sign in to comment.