From 2bc65ee76061ae6a94357fa59531a7ba631da908 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Sun, 12 Nov 2023 21:37:36 +0000 Subject: [PATCH] feat: add support for optional fields --- src/Form.php | 10 ++++++++++ tests/validation.test.php | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/Form.php b/src/Form.php index 4890137..f9bfccd 100644 --- a/src/Form.php +++ b/src/Form.php @@ -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; diff --git a/tests/validation.test.php b/tests/validation.test.php index e1b1e46..65b01f7 100644 --- a/tests/validation.test.php +++ b/tests/validation.test.php @@ -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'); +});