Dhara
Dhara

Reputation: 1481

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.

Upvotes: 3

Views: 3837

Answers (1)

AsgarAli
AsgarAli

Reputation: 2211

// 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>";
        }
    }
}

Upvotes: 5

Related Questions