yii2验证输入数组

时间:2015-10-18 13:27:02

标签: 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
        )
)

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

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

在视图中我有:

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

问题是,当我在第一个输入中使用“d”提交表单时,我在每个“类别”输入上都有错误: enter image description here

我做错了什么?

2 个答案:

答案 0 :(得分:2)

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

[
    // checks if every category ID is an integer
    ['categoryIDs', 'each', 'rule' => ['integer']],
]

此验证程序仅适用于数组属性。它验证是否可以通过指定的验证规则成功验证数组的每个元素。在上面的示例中,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.

答案 1 :(得分:0)

此答案适用于ajax请求方案

  

在您的控制器中

ConvertFrom-StringData
  

在你看来

use yii\base\Model;
use yii\widgets\ActiveForm;
use yii\web\Response;

public function actionCreate()
{
    $models = [
        'model1' => new Category, 
        'model2' => new Category, 
    ];

    if (Yii::$app->request->isAjax && Model::loadMultiple($models, Yii::$app->request->post())) {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $validate = [];
        $validate = array_merge(ActiveForm::validateMultiple($models), $validate);
        // If you need to validate another models, put below.
        // $validate = array_merge(ActiveForm::validate($anotherModel), $validate);

        return $validate;
    }

    if (Model::loadMultiple($models, Yii::$app->request->post())) {
        foreach($models as $key => $model) {
            $model->save();
        }
    }

    return $this->render('create', [
        'models' => $models,
    ]);
}
相关问题