yii2验证输入数组

Ily*_*ase 6 yii2

我有以下数据:

Array
(
    [category] => Array
        (
            [0] => d
            [1] => 100
            [2] => 100
            [3] => 100
        )

    [volume] => Array
        (
            [0] => 100
            [1] => 100
            [2] => 100
        )

    [urgency] => Array
        (
            [0] => 100
            [1] => 100
            [2] => 100
        )

    [importance] => Array
        (
            [0] => 100
            [1] => 100
            [2] => 100
        )
)
Run Code Online (Sandbox Code Playgroud)

我为它创建了DynamicModel规则"每个值应该是整数"(在2.0.4中添加).

$view_model = DynamicModel::validateData(compact('category', 'volume', 'urgency', 'importance'), [
        [['category', 'volume', 'urgency', 'importance'], 'each', 'rule' => ['integer']],
    ]);
Run Code Online (Sandbox Code Playgroud)

鉴于我有:

    <?= $form->field($model, 'category[0]')->textInput() ?>
    <?= $form->field($model, 'category[1]')->textInput() ?>
    <?= $form->field($model, 'category[2]')->textInput() ?>
    ...
    <?= $form->field($model, 'importance[2]')->textInput() ?>
Run Code Online (Sandbox Code Playgroud)

问题是,当我在第一个输入中使用"d"提交表单时,我在每个"类别"输入上都有错误: 在此输入图像描述

我做错了什么?

Ami*_*mar 3

您可以使用每个验证器信息:此验证器自版本 2.0.4 起可用。

[
    // checks if every category ID is an integer
    ['categoryIDs', 'each', 'rule' => ['integer']],
]
Run Code Online (Sandbox Code Playgroud)

该验证器仅适用于数组属性。它验证数组的每个元素是否可以通过指定的验证规则成功验证。在上面的示例中,categoryIDs 属性必须采用数组值,并且每个数组元素都将通过整数验证规则进行验证。

rule: an array specifying a validation rule. The first element in the array specifies the class name or the alias of the validator. The rest of the name-value pairs in the array are used to configure the validator object.
allowMessageFromRule: whether to use the error message returned by the embedded validation rule. Defaults to true. If false, it will use message as the error message.

Note: If the attribute value is not an array, it is considered validation fails and the message will be returned as the error message.
Run Code Online (Sandbox Code Playgroud)