Skip to content
This repository was archived by the owner on Jan 30, 2020. It is now read-only.

Optional input without value are valid #51

Merged
Merged
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
4 changes: 4 additions & 0 deletions src/FileInput.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,10 @@ public function isValid($context = null)
$allowEmpty = $this->allowEmpty();
$continueIfEmpty = $this->continueIfEmpty();

if (! $hasValue && ! $required) {
return true;
}

if (! $hasValue && $required && ! $this->hasFallback()) {
$this->setErrorMessage('Value is required');
return false;
Expand Down
4 changes: 4 additions & 0 deletions src/Input.php
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,10 @@ public function isValid($context = null)
return true;
}

if (! $hasValue && ! $required) {
return true;
}

if (! $hasValue && $required) {
$this->setErrorMessage('Value is required');
return false;
Expand Down
22 changes: 20 additions & 2 deletions test/InputTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,13 +167,31 @@ public function testRequiredWithoutFallbackAndValueNotSetThenFail()
{
$input = $this->input;
$input->setRequired(true);
$input->setContinueIfEmpty(true);

$this->assertFalse(
$input->isValid(),
'isValid() should be return always false when no fallback value, is required, and not data is set.'
);
$this->assertEquals(['Value is required'], $input->getMessages(), 'getMessages() should be empty because the input is valid');
$this->assertEquals(['Value is required'], $input->getMessages(), 'getMessages() value not match');
}

public function testNotRequiredWithoutFallbackAndValueNotSetThenIsValid()
{
$input = $this->input;
$input->setRequired(false);
$input->setAllowEmpty(false);
$input->setContinueIfEmpty(true);

// Validator should not to be called
$input->getValidatorChain()
->attach($this->createValidatorMock(null, null))
;
$this->assertTrue(
$input->isValid(),
'isValid() should be return always true when is not required, and no data is set. Detail: ' .
json_encode($input->getMessages())
);
$this->assertEquals([], $input->getMessages(), 'getMessages() should be empty because the input is valid');
}

public function testNotEmptyValidatorNotInjectedIfContinueIfEmptyIsTrue()
Expand Down