Custom Validation

Custom validation function does not work.

My model:




    public $current_pass;

    public $new_pass1;

    public $new_pass2;




    public function rules()

    {

        return [

            [['current_pass', 'new_pass1', 'new_pass2'], 'required'],

            [['new_pass1','new_pass2'], 'string', 'length' => [8, 12]],

            ['new_pass2', 'compare', 'compareAttribute' => 'new_pass1'],

            ['current_pass', 'check_pass'],

        ];

    }


    public function check_pass()

    {

        $old_pass=Yii::$app->security->generatePasswordHash($this->current_pass);

        $ut=Yii::$app->user->id;

        $saved_pass=utils::lookup("sys_users","id",$ut,"password_hash");

        if ($old_pass!=$saved_pass):

          $this->addError('current_pass', 'Palavra-passe atual incorreta');

        endif;

    }



Function check_pass never gets called. I used to do this very easily in Yii 1.1

What have changed? Thank you.

Custom validation has params "skipOnError" and "skipOnEmpty" set to true. You could try to set them to false.

Additional note: The most of validation methods have names started by "validate" like in "validateSomething" but I am note sure that Yii2 forces this naming convetion.

Thanks slinstj!

But that’s not it. I’ve tried change function name to validatePass and still doesn’t work. Also added


'skipOnEmpty'=> false, 'skipOnError'=> false. 

Nothing.

It’s like the validation isn’t there at all…

If you dont have xdebug (as it seems) you should try to add only


$this->addError(....)

or die(‘something’) in validation method just to check it being called. A reminder: It will work only in server side (you have not implemented the client-side one).

I’ve done that before my first post. It never gets called.

Could you please elaborate on that server-side idea? How do I specify that this particular validator must run server-side?

You dont specify, server-side is default. If your rules are triggering some error in client-side, server side validation is not being called, but only after all client-side are passing (when server side is run again).

Please, refer to this: http://www.yiiframework.com/doc-2.0/guide-input-validation.html#creating-validators

That was my understanding also.

With that beeing said I still don’t understand why the validation function never gets called.

GOT IT!

Model is fine.

In controller I wasn’t calling the validate() method… How stupid of me!




    public function actionChgpass()

    {


        $model = new ChgpassForm();


        if ($model->load(Yii::$app->request->post())):

            if ($model->validate()): <--- I was forgetting this!

               // do my stuff

            endif;




        endif;

        return $this->render('chgpass', [

            'model' => $model,

        ]);

    }