Yii2 EachValidator不起作用

时间:2015-11-12 09:59:56

标签: validation yii2

我有数组属性的表单。我试图使用eachValidator,但它不起作用。为了测试验证器,我创建了simle表单,但每个规则仍然不起作用。 型号:

<?php
namespace frontend\models;

use common\models\User;
use yii\base\Model;
use Yii;

class Test extends Model
{
    public $test;

    public function rules()
    {
        return [
            [['test'],'each','rule'=>['required']],
        ];
    }
    public function someFunc()
    {


        return null;
    }
}

控制器:

public function actionTest()
{
    $model = new Test();
    return $this->render('test', [
        'model' => $model,
    ]);
}

查看:

<?php

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;

?>

<div class="row">
    <div class="col-lg-12">
        <?php $form = ActiveForm::begin(['id' => 'test',]); ?>


            <?= $form->field($model, 'test[]')->textInput(['placeholder'=>'test'])->label('Test'); ?>
            <?= $form->field($model, 'test[]')->textInput(['placeholder'=>'test'])->label('Test'); ?>
            <?= $form->field($model, 'test[]')->textInput(['placeholder'=>'test'])->label('Test'); ?>

            <div class="form-group">
                <?= Html::submitButton('Get started', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
            </div>

        <?php ActiveForm::end(); ?>
    </div>
</div>

使用空字段成功提交表单。 我有Yii 2.0.6 enybody可以告诉我我做错了什么以及如何验证数组属性?

1 个答案:

答案 0 :(得分:1)

yii\validators\EachValidator无法在客户端验证数据,只需在控制器中调用validate()save()即可:

public function actionTest()
{
    $model = new Test();

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        // do what you want
    }

    return $this->render('test', [
        'model' => $model,
    ]);
}