somnambulist-tech / validation

A re-write of rakit/validation, a standalone validation library inspired by Laravel Validation
MIT License
44 stars 13 forks source link

URL validation rule is being executed even not being it isn't required #19

Closed andreoneres closed 1 year ago

andreoneres commented 1 year ago

The URL validation rule is being executed even not being it isn't required. This way, when not sending the 'hyperlink' key, there ends up being an error in the validation of the library's schema due to at null value.

To "resolve" this, I inform you that the value can be 'nullable', but the other rules don't require this.

Example:

$data = [
   "alt" => "Alt",
   "main" => true
];

$rules = [
   "alt" => "required|string",
   "hyperlink" => "url",
   "main" => "required|boolean",
];

When executing, this throws the exception:

Uncaught TypeError: Somnambulist\Components\Validation\Rules\Url::validateCommonScheme(): Argument #1 ($value) must be of type string, null given, called in .../vendor/somnambulist/validation/src/Rules/Url.php on line 38 and defined in .../vendor/somnambulist/validation/src/Rules/Url.php:53

dave-redfern commented 1 year ago

@andreoneres Hi, this is a known problem and stems from using strict_types. With rakit/validation these errors would not have been present as PHP would type-juggle. In fact, the next version of this library will invert the rules making them required unless specified otherwise as strictly speaking semantically defining a field with a rule implies it is required.

As you have already mentioned the fix is to use either sometimes if the field is completely optional and can be be ignored, or nullable if you wish to allow it to be null (not recommended in all honesty).

With all that said: I have checked the source and there is an explicit test for null handling in the Url rule. Could you check which version of the library you are using, and if necessary update to the most recent version? This should have been fixed in version 1.5.3.

andreoneres commented 1 year ago

@dave-redfern That's right, when updating to the latest version (1.7) the problem was solved. I had forgotten about this little detail :) Thanks!