2

我似乎无法正确验证数组:在我的示例中,每个音乐家都必须至少拥有一种乐器($musician->instruments 是乐器数组)。我尝试通过以下方式设置验证规则,但在任何情况下(包括当数组至少有一个值时)它们都不能验证。

一种

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

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

甚至 C 也无法验证

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

...

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

你如何设置它,以便如果验证器在数组为空时失败,并且在 count($musician->instruments) >= 1 时通过?

4

2 回答 2

0

锂文档:

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

当您要验证数组时,该规则不适用于您的情况。

第三个示例 desont' 工作是因为您正在测试数组是否存在,而不是它是否包含任何元素。

试试这个,它应该工作:

Validator::add('hasAtLeastOne', function($data) {
    return count($data);
});
于 2013-04-07T11:45:23.500 回答
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.

于 2013-07-18T17:12:47.260 回答