需要至少选择两个选项的验证规则

时间:2016-08-29 15:37:37

标签: validation yii2 yii2-validation

我有以下验证规则:

['dagen_ids', 'required', 'message' => 'Selecteer.', 'when' => function($model) {
    return $model->frequentie == 2;
}]

属性dagen_ids是一个由Select2小部件填充的数组(多选)。

我要实现的是拥有仅在$model->frequentie == 2时才需要的验证规则,用户需要选择至少 2个选项。

对于第二部分,我尝试了以下内联验证代码,但不幸的是它似乎没有任何效果。

['dagen_ids', function ($attribute, $params) {
    if (count($this->$attribute) < 2) {
        $this->addError($attribute, 'Selecteer minimaal 2 dagen.');
    }
}]

有人可以帮我一点,并向我解释如何结合这些验证规则吗?

修改

控制器:

public function actionView($id) 
{
    $planning = $this->findModel($id);
    $post = Yii::$app->request->post();

    if (Yii::$app->request->isAjax && $planning->load($post) && $planning->validate() && $planning->save()) {
            Yii::$app->session->setFlash('success', [
                'type' => 'success',
                'duration' => 10000,
                'icon' => 'fa fa-check',
                'message' => 'Opdracht is succesvol bijgewerkt.'.Html::button(Icon::show('hand-o-right', ['class' => ''], Icon::FA). Yii::t('app', 'View'), ['class' => 'btn btn-sm btn-success modalButton pull-right', 'data-notify' => 'dismiss', 'data-content' => Url::to(['planning/view', 'id' => $id])]),
                'title' =>  Html::tag('span', 'Opdracht bijgewerkt', ['style' => 'font-weight: bold;']),
                'positonY' => 'top',
                'positonX' => 'right'
            ]);
    }
    else {
        return $this->renderAjax('view', ['planning' => $planning]); 
    }
}

JQuery的:

$('body').on('beforeSubmit', 'form#view_form', function () {

    var form = $(this);
    // return false if form still have some validation errors
    if (form.find('.has-error').length) {
        return false;
    }

    // submit form
    $.ajax({
        url: form.attr('action'),
        data: form.serialize(),
        type: 'post'
    }).done(function(){
        $('.modal').modal('hide');
        console.log('Form send!');
        $.pjax.reload({
            container: '#planner_grid', 
            timeout: 10000, 
            replace: false
        });
    }).fail(function(){
        console.log('Server error...');
    }); 

    return false;
});

2 个答案:

答案 0 :(得分:1)

引自The Definitive Guide to Yii 2.0: Validating Input - Inline Validators

  

注意:默认情况下,如果内联验证器的关联属性接收到空输入或者某些验证规则已失败,则不会应用内联验证器。如果要确保始终应用规则,可以在规则声明中将skipOnEmpty和/或skipOnError属性配置为false。

因此,您可能需要将这两个属性添加到false,并且您还可以更改条件,以便检查frequentie上的值:

['dagen_ids', function ($attribute, $params) {
    if ($this->frequentie == 2 && count($this->$attribute) < 2) {
        $this->addError($attribute, 'Selecteer minimaal 2 dagen.');
    }
}, 'skipOnEmpty' => false, 'skipOnError' => false]

这样您就不需要有2种不同的验证规则。

答案 1 :(得分:0)

终于想通了..

在这种情况下,使用内联/独立验证器,我需要进行Ajax验证。

我正在使用DetailView插件,它看起来像这样:

echo DetailView::widget([
    'model' => $planning,
    'attributes' => $attributes,
    'mode' => 'view',
    'panel' => [
        'heading' => $planning->stopTitel, 
        'type' => DetailView::TYPE_PRIMARY,
    ],
    'bordered' => false,
    'responsive' => true,
    'hover' => true,
    'fadeDelay'=> 800,
    'deleteOptions' => [
        'params' => ['id' => $planning->planning_id, 'delete' => true],
        'url' => ['delete']
    ],
    'container' => ['id' => 'opdracht-bewerken'],
    'formOptions' => ['id' => 'view_form', 'action' => Url::current(['#' => 'opdracht-bewerken']), 'validationUrl' => Url::toRoute(['validate-form']), 'enableClientValidation' => true, /*'enableAjaxValidation' => true*/], // If you want Ajax validation on the whole form, uncomment this.
]);

但我只想要一个字段进行Ajax验证,所以在我的情况下我需要将以下内容添加到我的dagen_ids字段中:

'fieldConfig' => ['enableAjaxValidation' => true]Documentation

我的控制器看起来像:

use yii\web\Response;
use yii\helpers\Json;
use kartik\widgets\ActiveForm;

    public function actionView($id) 
    {
        $planning = $this->findModel($id);
        $post = Yii::$app->request->post();

        if ($planning->load($post) && $planning->save()) {
            Yii::$app->session->setFlash('success', [
                'type' => 'success',
                'duration' => 10000,
                'icon' => 'fa fa-check',
                'message' => 'Opdracht is succesvol bijgewerkt.'.Html::button(Icon::show('hand-o-right', ['class' => ''], Icon::FA). Yii::t('app', 'View'), ['class' => 'btn btn-sm btn-success modalButton pull-right', 'data-notify' => 'dismiss', 'data-content' => Url::to(['planning/view', 'id' => $id])]),
                'title' =>  Html::tag('span', 'Opdracht bijgewerkt', ['style' => 'font-weight: bold;']),
                'positonY' => 'top',
                'positonX' => 'right'
            ]);
        }
        else {
            return $this->renderAjax('view', ['planning' => $planning]); 
        }
    }

    public function actionValidateForm() {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $planning = new Planning();
        $post = Yii::$app->request->post();

        $planning->load($post);
        return ActiveForm::validate($planning);
    }

我的独立验证工具:

namespace backend\components\validators;

use yii\validators\Validator;

class DagenValidator extends Validator
{
    public function validateAttribute($model, $attribute)
    {
        if ($model->frequentie == 2 && count($model->$attribute) < 2) {
            $this->addError($model, $attribute, 'Selecteer minimaal 2 dagen.');
        }
    }
}

现在,在我的Planning模型中,我可以添加以下规则:

['dagen_ids', DagenValidator::className(), 'skipOnEmpty' => false, 'skipOnError' => false]