Validations do not handle nil values
grey280 opened this issue · 3 comments
Describe the bug
validations.add("foo", as: String?.self, is: .nil || !.nil)
throws a validation error when trying to validate a nil
value.
To Reproduce
Steps to reproduce the behavior:
- Create a
Content
class/struct and add a validation for aString?
property usingis: .nil || !.nil
as the validation requirement - Create an endpoint that validates your new class/struct.
- Send a request to the endpoint that either explicitly or implicitly has
nil
as the value of theString?
property. - Observe the (incorrect) validation error thrown.
Expected behavior
Since the expectation is a tautology, it should always pass validation.
Environment
- Vapor Framework version: 4.76.3
- Vapor Toolbox version: 18.7.1
- OS version: macOS 13.4
Additional context
I've simplified this case down, as I originally had it doing a sane validation, but the tautological version is a better demonstration of the issue. (I was originally trying a is: .nil || .empty || .pattern(bar)
check, and found it to always fail when given a nil
even though that was an explicitly-allowed value.)
I think this is a quirk of the validation library and our docs. If you want to verify something is either nil
or matches a validator you can pass a required
flag to the validation. Does that work for you?
Indeed that does, thanks Tim! Another read-through of the docs, I do see that it mentions the required
flag, but it may be worth specifically calling out the use of that for optional types, as: String.self ... required: false
rather than as: String?.self
?
Yeah the docs could be a bit better - if you fancy a PR then great!