Skip to content

Commit

Permalink
Added nullable rule
Browse files Browse the repository at this point in the history
Thanks to @Validation
  • Loading branch information
gdarko committed Jun 30, 2020
1 parent 7cf62c5 commit 22e8164
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/Rules/Nullable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php


namespace DG\Validation\Rules;


use DG\Validation\Rule;

class Nullable extends Rule
{
/**
* Check the $value is valid
*
* @param mixed $value
* @return bool
*/
public function check($value): bool
{
return true;
}
}
4 changes: 4 additions & 0 deletions src/Validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,10 @@ protected function validateAttribute(Attribute $attribute)
$value = $this->getValue($attributeKey);
$isEmptyValue = $this->isEmptyValue($value);

if ($attribute->hasRule('nullable') && $isEmptyValue) {
$rules = [];
}

$isValid = true;
foreach ($rules as $ruleValidator) {
$ruleValidator->setAttribute($attribute);
Expand Down
1 change: 1 addition & 0 deletions src/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ protected function registerBaseValidators()
'digits_between' => new Rules\DigitsBetween,
'defaults' => new Rules\Defaults,
'default' => new Rules\Defaults, // alias of defaults
'nullable' => new Rules\Nullable,
];

foreach ($baseValidator as $key => $validator) {
Expand Down
40 changes: 40 additions & 0 deletions tests/ValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1494,4 +1494,44 @@ public function testRuleUploadedFileInvalidMessages()
$expectedMessage = "The Sample file type must be 'jpeg', 'png', atau 'bmp'";
$this->assertEquals($validation->errors()->first('sample'), $expectedMessage);
}

public function testIgnoreNextRulesWithNullableRule()
{
$emptyFile = [
'name' => '',
'type' => '',
'size' => '',
'tmp_name' => '',
'error' => UPLOAD_ERR_NO_FILE
];

$invalidFile = [
'name' => 'sample.txt',
'type' => 'plain/text',
'tmp_name' => __FILE__,
'size' => 1000,
'error' => UPLOAD_ERR_OK,
];

$data1 = [
'file' => $emptyFile,
'name' => ''
];

$data2 = [
'file' => $invalidFile,
'name' => '[email protected]'
];

$rules = [
'file' => 'nullable|uploaded_file:0,500K,png,jpeg',
'name' => 'nullable|email'
];

$validation1 = $this->validator->validate($data1, $rules);
$validation2 = $this->validator->validate($data2, $rules);

$this->assertTrue($validation1->passes());
$this->assertFalse($validation2->passes());
}
}

0 comments on commit 22e8164

Please sign in to comment.