public function actionAdHocValidation() { $model = DynamicModel::validateData([ 'username' => 'hippo', 'email' => '[email protected]' ], [ [['username', 'email'], 'string', 'max' => 12], ['email', 'email'], ]); if ($model->hasErrors()) { var_dump($model->errors); } else { echo "success"; } }
第2步 -在Web瀏覽器的位址列中輸入URL:http://localhost:8080/index.php?r=site/ad-hoc-validation ,這時會看到一個錯誤資訊,因為電子郵件(email)有超過 12 個字元。
內聯驗證器通過模型法或匿名函式定義。如果屬性無法驗證,應該呼叫yii\base\Model::addError() 方法來儲存錯誤訊息。
<?php namespace app\models; use Yii; use yii\base\Model; class RegistrationForm extends Model { public $username; public $password; public $email; public $country; public $city; public $phone; public function rules() { return [ ['city', 'validateCity'] ]; } public function validateCity($attribute, $params) { if (!in_array($this->$attribute, ['Haikou', 'Guangzhou'])) { $this->addError($attribute, 'The city must be either "London" or "Paris".'); } } } ?>
一個獨立的驗證器一般是擴充套件 yii\validators\Validator 類。要實現驗證邏輯,應該重寫 yii\validators\Validator::validateAttribute() 方法。
<?php namespace app\components; use yii\validators\Validator; class CityValidator extends Validator { public function validateAttribute($model, $attribute) { if (!in_array($model->$attribute, ['Paris', 'London'])) { $this->addError($model, $attribute, 'The city must be either "Haikou" or "Guangzhou".'); } } } ?>
<?php namespace app\models; use app\components\CityValidator; use Yii; use yii\base\Model; class RegistrationForm extends Model { public $username; public $password; public $email; public $country; public $city; public $phone; public function rules() { return [ ['city', CityValidator::className()] ]; } } ?>