S
S
Sergey2016-07-20 00:22:23
Yii
Sergey, 2016-07-20 00:22:23

Why doesn't native validation work in yii2?

gentlemen, there is a problem: I do my own validation, add to the rules:

['role', 'required'],
['role', 'validateRole'],

Next, the method:
// Role validation:
    public function validateRole($attribute, $params) {
    	if (!in_array($this->$attribute, ['admin','distributor','reseller','customer'])) {
            $this->addError($attribute, 'Wrong Role');
        }
    }

In this case, only required on the frontend works.
I even tried doing this:
// Role validation:
    public function validateRole($attribute, $params) {
            $this->addError($attribute, 'Wrong Role');
    }

but at the same time, the frontend is empty, no errors.
Even if inside ValidateRole just write die(); - nothing crashes, but if you remove the validateRole method, but leave it in rules, then YII gives an error
Exception 'ReflectionException' with message 'Class validateRole does not exist'

But why class?
What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrew, 2016-07-22
@butteff

why reinvent the wheel?

['role', 'required'],
['role', 'in', 'range' => ['admin', 'distributor', 'reseller', 'customer'], 'message' => 'Wrong Rule'],

N
Nikita, 2016-07-20
@bitver

Press submit and you will get an error. And on the client you need to do clientValidation

A
Andrey Pavlenko, 2016-07-20
@Akdmeh

Sergey : yes, below you were answered correctly. It shouldn't have worked on the frontend, sorry, I just didn't notice. For the frontend, you need to write your own rules, see
www.yiiframework.com/doc-2.0/yii-validators-valida...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question