簡體   English   中英

Yii2中的自定義屬性驗證

[英]Custom attribute validation in Yii2

我那里有模型表單( SomeForm )和自定義驗證功能:

use yii\base\Model; 
class SomeForm extends Model
{
      public $age;
      public function custom_validation($attribute, $params){
             if($this->age < 18){
                    $this->addError($attribute, 'Some error Text');
                    return true;
             }
             else{
                     return false;
             }
      }
      public function rules(){
             return [
                 ['age', 'custom_validation']
             ];
      }
}

我在rules()函數中使用了這個custom_validation ,但是即使提交任何具有age屬性的值,表單也是如此。

形式如下:

age.php

<?php $form = ActiveForm::begin(); ?>
    <?= $form->field($model, 'age')->label("Age") ?>
    <div class="form-group">
        <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
    </div>
    <?php ActiveForm::end(); ?>

和控制器:

use yii\web\Controller;

class SomeController extends Controller
{
     //this controller is just for rendering
     public function actionIndex(){
             return $this->render('age');
     }
     public function actionSubmit(){
             $model = new SomeForm();
             if($model->load(Yii::$app->request->post()){
                   //do something here
             }
     }
}

您只需將錯誤添加到屬性中就足夠了,而無需返回任何內容。

2.0.11版本開始,您可以使用yii\\validators\\InlineValidator::addError()添加錯誤,而不是使用$this 這樣,可以立即使用yii\\i18n\\I18N::format()格式化錯誤消息。

在錯誤消息中使用{attribute}{value}來引用屬性標簽(無需手動獲取)和屬性值:

我懷疑您遇到的問題是您缺少$formModel->validate() ,因為上面給出的模型擴展了yii\\base\\Model而不是\\yii\\db\\ActiveRecord並且您必須保存其他一些ActiveRecord模型,要在保存ActiveRecord模型之前驗證此FormModel ,必須調用$formModel->validate()來檢查是否提供了有效輸入,並在將post數組加載到模型后觸發模型驗證。

還要注意的另一點是,默認情況下,如果內聯驗證器的關聯屬性接收到空輸入或某些驗證規則已失敗,則不會應用它們。 如果要確保始終應用規則,則可以在規則聲明中將skipOnEmpty和/或skipOnError屬性配置為false

您的模型看起來應該像下面所示,如果這不是故意的或由於示例代碼而導致的,則模型定義中缺少namespace 只需根據名稱空間所在的路徑來更新它即可。

namespace frontend\models;

use yii\base\Model; 
class SomeForm extends Model
{
      public $age;
      const AGE_LIMIT=18;

      public function rules(){
             return [
                 ['age', 'custom_validation','skipOnEmpty' => false, 'skipOnError' => false]
             ];
      }

      public function custom_validation($attribute, $params,$validator){
          if($this->$attribute< self::AGE_LIMIT){
             $validator->addError($this, $attribute, 'The value "{value}" is not acceptable for {attribute}, should be greater than '.self::AGE_LIMIT.'.');
           }
      }
}

您的controller/action應類似於

public function actionTest()
    {
        //use appropriate namespace
        $formModel = new \frontend\models\SomeForm();
        $model= new \frontend\models\SomeActiveRecordModel();

        if ($formModel->load(Yii::$app->request->post()) && $model->load(Yii::$app->request->post())) {
            if ($formModel->validate()) {
             // your code after validation to save other ActiveRecord model
             if($model->save()){
              Yii::$app->session->setFlash('success','Record added succesfully.')
             }
            }
        }

        return $this->render('test', ['model' => $model,'formModel'=>$formModel]);
    }

視圖文件中的輸入字段age應使用$formMoedl對象

echo $form->field($formModel, 'age')->textInput();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM