2

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?

Rosano
  • 21
  • 2

2 Answers2

0

Lithium docs:

`notEmpty`: Checks that a string contains at least one non-whitespace character.

As you want to validate an array, that rule doesn't work in your case.

The third example desont' work either because you are testing that the array exists, not if it contains any elements.

Try with this, it should work:

Validator::add('hasAtLeastOne', function($data) {
    return count($data);
});
jfcalcerrada
  • 11
  • 2
  • 4
0

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.

Rosano
  • 21
  • 2