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?

2 Answers 2

2

Change Your Rule Property As:

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

To know Skip On Empty

Sign up to request clarification or add additional context in comments.

Comments

0

Everything in model looks OK. May be try

echo $model->getErrors();

in your controller.May be can help you.

1 Comment

How do I use this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.