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

Attribute search in multidimensional array #16

Closed andreoneres closed 1 year ago

andreoneres commented 1 year ago

When using the required_if validation rule on a multidimensional array, the parameter is not found because the search is done considering the complete array, instead of the specific item.

Example:

$data = [
  [
    "alt" => "Alt",
    "hyperlink" => "https://google.com",
    "main" => true
  ]
];

$rules = [
   "*.alt" => "required|string",
   "*.hyperlink" => "url",
   "*.main" => "boolean",
   "*.title" => "required_if:main,true|string",
];

In this way, even passing the main attribute, the title attribute doesn't become required.

dave-redfern commented 1 year ago

@andreoneres Thanks for your bug report. This is actually a deficiency in the documentation. Array data is treated a little differently than normal and in this instance the required_if needs to reference the field *.main. If you add that you should find the validation works as intended.

Internally what happens with array style rules is that each item in the array is mapped out to a 0..<n+1> set of rules and a special "parent" property is set. Referencing other rules for that item then requires knowing which index it should match. Right now it would look for main as a key in the main data array - not the sub-items.

I will update the documentation to give explicit instructions when dealing with array data.

dave-redfern commented 1 year ago

@andreoneres I have added explicit docs regarding arrays. Please let me know if I have missed something important or if something is not working: https://github.com/somnambulist-tech/validation#validating-array-data

andreoneres commented 1 year ago

All right. Thanks! Regarding the change in the documentation, I believe it was clear enough.