[ // required, specifies which attributes should be validated ['attr1', 'attr2', ...], // required, specifies the type a rule. 'type_of_rule', // optional, defines in which scenario(s) this rule should be applied 'on' => ['scenario1', 'scenario2', ...], // optional, defines additional configurations 'property' => 'value', ... ]
核心驗證規則 ? boolean, captcha, compare, date, default, double, each, email, exist, file, filter, image, ip, in, integer, match, number, required, safe, string, trim, unique, url。
<?php namespace app\models; use Yii; use yii\base\Model; class RegistrationForm extends Model { public $username; public $password; public $email; public $phone; public function rules() { return [ // the username, password, email, country, city, and phone attributes are //required [['username' ,'password', 'email', 'phone'], 'required'], // the email attribute should be a valid email address ['email', 'email'], ]; } } ?>
我們已經宣告 registration 表單模型。該模型有五個屬性 ? username, password, email, country, city 和 phone。它們都必需的以及 email 屬性必須是一個有效的電子郵件地址。
public function actionRegistration() { $model = new RegistrationForm(); return $this->render('registration', ['model' => $model]); }
第4步 - 新增 registration 表檢視。 在 views/site 檔案夾內部,建立一個 registration.php 檔案並使用下面的程式碼。
<?php use yii\bootstrap\ActiveForm; use yii\bootstrap\Html; ?> <div class = "row"> <div class = "col-lg-5"> <?php $form = ActiveForm::begin(['id' => 'registration-form']); ?> <?= $form->field($model, 'username') ?> <?= $form->field($model, 'password')->passwordInput() ?> <?= $form->field($model, 'email')->input('email') ?> <?= $form->field($model, 'phone') ?> <div class = "form-group"> <?= Html::submitButton('提交', ['class' => 'btn btn-primary', 'name' => 'registration-button']) ?> </div> <?php ActiveForm::end(); ?> </div> </div>
public function rules() { return [ // the username, password, email, country, city, and phone attributes are required [['password', 'email', 'country', 'city', 'phone'], 'required'], ['username', 'required', 'message' => 'Username is required'], // the email attribute should be a valid email address ['email', 'email'], ]; }
第7步- 開啟轉到 http://localhost:8080/index.php?r=site/registration ,然後單擊提交按鈕。你會發現,username 屬性的錯誤資訊發生了變化。
yii\base\Model::beforeValidate(): 觸發一個
yii\base\Model::EVENT_BEFORE_VALIDATE 事件.
yii\base\Model::afterValidate(): 觸發一個
yii\base\Model::EVENT_AFTER_VALIDATE 事件.
public function rules() { return [ // the username, password, email, country, city, and phone attributes are required [['password', 'email', 'country', 'city', 'phone'], 'required'], ['username', 'required', 'message' => 'Username is required'], ['country', 'trim'], ['city', 'default'], // the email attribute should be a valid email address ['email', 'email'], ]; }
public function rules() { return [ ['city', 'default', 'value' => 'Haikou'], ]; }