Search code examples
lithium

Lithium Validator does not process arrays?


I cannot seem to get an array to validate properly: in my example, every musician must have at least one instrument ($musician->instruments is an array of instruments). I have tried setting up validation rules in the following ways, but none of them validate under any circumstances (including when the array has at least one value).

A

public $validates = array(
    'name' => 'Required',
    'instruments' => 'Required'
);

B

public $validates = array(
    'name' => 'Required',
    'instruments' => array(
        array(
            'notEmpty',
            'message' => 'Required'
        )
    )
);

even C fails to validate

Validator::add('hasAtLeastOne', function($value) {
    return true;
});

...

public $validates = array(
    'name' => 'Required',
    'instruments' => array(
        array(
            'hasAtLeastOne',
            'message' => 'Required'
        )
    )
);

How do you set it up so that if the validator fails if the array is empty, and passes if count($musician->instruments) >= 1?


Solution

  • This checks for the presence of the first instrument in the array, which implies that there is at least one.

    public $validates = array(
        'name' => 'Required',
        'instruments.0' => 'Required',
    );
    

    This will not associate the error with the 'instruments' field, so to make it play nice with the form, it needs to be copied over:

    $errors = $binding->errors();
    if ($errors['instruments.0']) {
        $errors['instruments'] = $errors['instruments.0'];
        unset($errors['instruments.0']);
        $binding->errors($errors);
    }
    

    This was unobvious and not intuitive for me, but it seems to be the most "built-in" way of dealing with validating arrays.