phpcodeigniter-4

Using validation rule 'differs' on Array Data


My controller receives JSON as POST data and passes it to the validator. There is some strange behavior using the differs[field_name]rule. I try to let the validator check, if one of the optional alias fields matches the value of name. But they all differ, so it should pass - I thought.
This is the stripped down controller:

class Test extends BaseController
{

    public function index()
    {
        // Use POST data
        $postData = $this->request->getJSON(TRUE);

        // Checks whether the submitted data passed the validation rules.
        $rules = [
            'name' => 'permit_empty',
            'emailAddress' => 'permit_empty|valid_email',
            'alias.*' => [
                'rules' => 'permit_empty|differs[name]',
                'errors' => [
                    'differs' => 'You cannot use your name as alias'
                ]
            ],
        ];
        if ($this->validateData($postData, $rules)) {
            // Validation passed
            echo PHP_EOL.'validation: PASSED';
        } else {
            // Validation failed
            $errors = $this->validator->getErrors();
            print_r($errors);
        }
    }
}

To test the controller I POST this JSON to it:

{
  "name": "Princess Peach",
  "emailAddress": "valid@example.com",
  "alias": [ "Princess Toadstool", "Peach" ]
}

Which gets passed as array to the validator:

array(3) {
  ["name"]=>
    string(14) "Princess Peach"
  ["emailAddress"]=>
    string(17) "valid@example.com"
  ["alias"]=>
    array(2) {
      [0]=>
        string(18) "Princess Toadstool"
      [1]=>
        string(5) "Peach"
      }
}

Which fails validation:

Array
(
  [alias.0] => You cannot use your name as alias
  [alias.1] => You cannot use your name as alias
)

Solution

  • Bug fixed in #9103, the code from above is now working.