Skip to content

Commit 1f784f4

Browse files
committed
Revert "Revert "Add option to check for value presence, while allowing empty values""
This reverts commit 1c62b45.
1 parent 1c62b45 commit 1f784f4

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/Validator.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,10 @@ public function __construct(
3434
* Note: strings are trimmed prior to check, and values that empty() would return true for (like '0') are considered
3535
* to be present (because we check strlen(trim($value))).
3636
*/
37-
public function present(string $field_name): bool
37+
public function present(
38+
string $field_name,
39+
bool $allow_empty = false,
40+
): bool
3841
{
3942
if (empty($field_name)) {
4043
throw new InvalidArgumentException(
@@ -46,6 +49,10 @@ public function present(string $field_name): bool
4649
return $this->failPresenceValidation($field_name);
4750
}
4851

52+
if ($allow_empty && empty($this->field_values[$field_name])) {
53+
return true;
54+
}
55+
4956
if (is_string($this->field_values[$field_name])) {
5057
if (mb_strlen(trim($this->field_values[$field_name])) > 0) {
5158
return true;

test/src/PresenceValidatorTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,21 @@ public function testPass()
4242
$this->assertCount(0, $name_errors);
4343
}
4444

45+
public function testPassAllowEmpty()
46+
{
47+
$validator = new Validator($this->connection, 'writers', null, null, ['name' => '']);
48+
49+
$is_present = $validator->present('name', true);
50+
51+
$this->assertTrue($is_present);
52+
$this->assertFalse($validator->hasErrors());
53+
54+
$name_errors = $validator->getFieldErrors('name');
55+
56+
$this->assertIsArray($name_errors);
57+
$this->assertCount(0, $name_errors);
58+
}
59+
4560
/**
4661
* Test validation failure.
4762
*/

0 commit comments

Comments
 (0)