Conditional validation
There are cases when it is necessary to enable or disable specific validation rules in the model. Yii2 provides a mechanism to do that.
Getting ready
Create a new application by using the Composer package manager, as described in the official guide at http://www.yiiframework.com/doc-2.0/guide-startinstallation.html.
How to do it...
Create a form file,
@app/models/DeliveryForm.php
, as follows:<?php namespace app\models; use app\components\WordsValidator; use yii\base\Model; class DeliveryForm extends Model { const TYPE_PICKUP = 1; const TYPE_COURIER = 2; public $type; public $address; public function rules() { return [ ['type', 'required'], ['type', 'in', 'range'=>[self::TYPE_PICKUP, self::TYPE_COURIER]], ['address', 'required', 'when' => function ($model) { return $model->type == self::TYPE_COURIER; }, 'whenClient' => "function (attribute, value) { ...