0

How to implement custom validation in yii2?

My code in model rules is

public function rules()
{
    return [
        [['product_price'], 'checkMaxPrice']
    ];
}

public function checkMaxPrice($attribute,$params)
{
    if($this->product_price > 1000) {
        $this->addError($attribute,'Price must be less than 1000');
    }
}

Anything else I have to do in view?

Double H
  • 4,120
  • 1
  • 15
  • 26
kritika555
  • 183
  • 1
  • 4
  • 15

2 Answers2

2

Change Your Rule Property As:

public function rules()
{
    return [
        [['product_price'], 'checkMaxPrice' ,'skipOnEmpty' => false]
    ];
}

To know Skip On Empty

Double H
  • 4,120
  • 1
  • 15
  • 26
0

Everything in model looks OK. May be try

echo $model->getErrors();

in your controller.May be can help you.

Mad Adh
  • 95
  • 9