Skip to content

Commit 2bc65ee

Browse files
committed
feat: add support for optional fields
1 parent fa9aece commit 2bc65ee

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/Form.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,16 @@ public static function validate(array $data, array $rules)
187187
}
188188
}
189189

190+
if (in_array('optional', $userRules)) {
191+
$userRules = array_filter($userRules, function ($rule) {
192+
return $rule !== 'optional';
193+
});
194+
195+
if (!isset($data[$field])) {
196+
continue;
197+
}
198+
}
199+
190200
foreach ($userRules as $rule) {
191201
if (empty($rule)) {
192202
continue;

tests/validation.test.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,21 @@
4242

4343
expect(Form::errors())->toHaveKey('test3');
4444
});
45+
46+
test('fields can be marked as optional', function () {
47+
$itemsToValidate = [];
48+
49+
$validatedData = Form::validate($itemsToValidate, ['test4' => 'optional|email']);
50+
51+
expect($validatedData)->toBe($itemsToValidate);
52+
expect(Form::errors())->not->toHaveKey('test4');
53+
});
54+
55+
test('optional fields are validated correctly if provided', function () {
56+
$itemsToValidate = ['test5' => ''];
57+
58+
$validatedData = Form::validate($itemsToValidate, ['test5' => 'optional|email']);
59+
60+
expect($validatedData)->toBe(false);
61+
expect(Form::errors())->toHaveKey('test5');
62+
});

0 commit comments

Comments
 (0)