Yii2 Tips 25 : All About Form Validation
Model
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<?php namespace common\models; use Yii; use yii\base\Model; class ValidationForm extends \backend\models\Branches { public $email; public $url; public $boolean; public $boolean2; public $password; public $password_repeat; public $compare; public $integer; public $inrange; /** * @inheritdoc */ public function rules() { return [ [['email'],'email'], [['url'],'url'], [['boolean'],'boolean'], [['boolean2'],'boolean','trueValue'=>'male','falseValue'=>'female'], [['password_repeat'],'compare','compareAttribute'=>'password'], [['compare'],'compare','compareValue' => 30, 'operator' => '>='], [['integer'],'integer','min' => 10, 'max'=>20], [['inrange'],'in','range'=>['one','two','three'],'not'=>false], ]; } public function attributeLabels() { return [ 'email' => Yii::t('app', 'Email'), ]; } } |
Controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?php namespace frontend\controllers; use Yii; class ValidationController extends \yii\web\Controller { public function actionIndex(){ return $this->render('index'); } public function actionValidate(){ $model = new \common\models\ValidationForm(); if($model->load(Yii::$app->request->post())){ echo "<pre>"; print_r($model); echo "</pre>"; die(); } return $this->render('_form',[ 'model' => $model, ]); } } |
View
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<?php use yii\widgets\ActiveForm; use yii\helpers\Html; ?> <div class="dummy-form"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model,'email')->textInput();?> <?= $form->field($model,'url')->textInput();?> <?= $form->field($model,'boolean')->textInput();?> <?= $form->field($model,'boolean2')->textInput();?> <?= $form->field($model,'password')->textInput();?> <?= $form->field($model,'password_repeat')->textInput();?> <?= $form->field($model,'compare')->textInput();?> <?= $form->field($model,'integer')->textInput();?> <?= $form->field($model,'inrange')->textInput();?> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div> |