Search code examples
yii2-advanced-appcustom-validators

custom validation not work in yii2


I have used custom validation.But it is not working. Here is my model

class Manufacture extends \yii\db\ActiveRecord
{
public function rules()
    {
        return [
             [['model_no'], 'safe'],
             ['model_no', 'customValidation', 'skipOnEmpty' => false, 'skipOnError' => false],
          ];
    }

    public function customValidation($attribute, $params)
    {

       if($this->model_no=='test')
        {
         $this->addError($attribute,'add proper data.');
        }
    }

}

In controller

public function actionCreate()
    {
        if ($model->load(Yii::$app->request->post())) {
              if ($model->validate()) { 
                //some code
             }
        }
}

Here i have add attribute in safe but still my error not displayed in view form.


Solution

  • // MODLE CODE
    class Manufacture extends \yii\db\ActiveRecord
    {
    
        public function rules()
        {
            return [
                [['model_no'], 'required'],
                ['model_no', function ($attribute, $params)
                    {
    
                        if ($this->$attribute == 'test')
                        {
                            $this->addError($attribute, 'You have entered test');
                        }
                        else
                        {
                            $this->addError($attribute, "You have not entered test but you have entered {$this->$attribute} ");
                        }
                    }],
            ];
        }
    
    }
    
    // CONTROLLER CODE
    public function actionCreate()
    {
        $model = new Manufacture();
        if ($model->load(Yii::$app->request->post()))
        {
            if ($model->validate())
            {
                //HERE YOU CAN WRITE YOUR CODE TO SAVE THE DATA
            }
            else
            {
                // HERE YOU CAN PRINT THE ERRORS OF MODEL
                echo "<pre>";
                print_r($model->getErrors());
                echo "</pre>";
            }
        }
    }