Skip to content

Commit

Permalink
feat: add support for optional fields
Browse files Browse the repository at this point in the history
  • Loading branch information
mychidarko committed Nov 12, 2023
1 parent fa9aece commit 2bc65ee
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/Form.php
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,16 @@ public static function validate(array $data, array $rules)
}
}

if (in_array('optional', $userRules)) {
$userRules = array_filter($userRules, function ($rule) {
return $rule !== 'optional';
});

if (!isset($data[$field])) {
continue;
}
}

foreach ($userRules as $rule) {
if (empty($rule)) {
continue;
Expand Down
18 changes: 18 additions & 0 deletions tests/validation.test.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,21 @@

expect(Form::errors())->toHaveKey('test3');
});

test('fields can be marked as optional', function () {
$itemsToValidate = [];

$validatedData = Form::validate($itemsToValidate, ['test4' => 'optional|email']);

expect($validatedData)->toBe($itemsToValidate);
expect(Form::errors())->not->toHaveKey('test4');
});

test('optional fields are validated correctly if provided', function () {
$itemsToValidate = ['test5' => ''];

$validatedData = Form::validate($itemsToValidate, ['test5' => 'optional|email']);

expect($validatedData)->toBe(false);
expect(Form::errors())->toHaveKey('test5');
});

0 comments on commit 2bc65ee

Please sign in to comment.