framework: Validator doesn't keeps numeric indexes on rules

  • Laravel Version: 5.5.26
  • PHP Version: 7.1
  • Database Driver & Version: irrelevant

Description:

Laravel validator does not keep numeric indexes on validation rules.

Steps To Reproduce:

        $validator = Validator::make(['c0'=>false,'c1'=>true], ['c0'=>'false']);
        $this->assertTrue($validator->passes());
        
        $validator = Validator::make(['c0'=>false,'c1'=>true], ['c1'=>'true']);
        $this->assertTrue($validator->passes());
        
        $validator = Validator::make([0=>false,1=>true], [0=>'false']);
        $this->assertTrue($validator->passes());
        
        $validator = Validator::make([0=>false,1=>true], [0=>'false', 1=>'true']);
        $this->assertTrue($validator->passes());
        
        $validator = Validator::make([0=>false,1=>true], [1=>'true']);
        $this->assertTrue($validator->passes());// this fails

Reason:

https://github.com/illuminate/validation/blob/master/Validator.php#L807 array_merge_recursive does keep associative array keys only for string keys, and not for numeric keys.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 1
  • Comments: 15 (6 by maintainers)

Most upvoted comments

I’m trying to set up a validation where the input is not a regular form, but an array. (generated input) The applied validation is also generated (from db)

Real life example: using this validation to import large csv files with lots of columns and rows, with validation/feedback for the columns.

To keep things simple, I don’t want to use names on them. Therefore a simple numeric-indexed array would be the data, and also the validation rules:

$rules = ["rule0", "rule1", "rule2"];//generated
foreach(getData() as $data){
  $validator = Validator::make($data, $rules);
}

I’m generating the ruleset once, and then have a lot of data rows and colls. To optimize it a bit, I’m trying to remove the empty rules. Therefore the array becomes jagged. (eg. rule1 is not neeeded):

$rules = [0=>"rule0", 2=>"rule2"];

and here is the issue. Laravel interprets the $rules above in the following way:

[0=>"rule0", 1=>"rule2] (or simply ["rule0", "rule2"] )

just simply reorganizes the array.

What is true? There’s no validation rule named true!